Refresh a DIV content after faded it out - javascript

I got X DIV (TopRowRight1, TopRowRight2, TopRowRight3...) , each containing a different Google Geochart generated by a php page : GeochartPerProvince.php?template=X.
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
jQuery().ready(function(){
getResult(1);
setInterval("getResult(1)",10000);
getResult(2);
setInterval("getResult(2)",10000);
getResult(3);
setInterval("getResult(3)",10000);
});
jQuery(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 5000)
});
Every 5 seconds, i fade out one and fade in the next one. This works perfectly.
For now, the php page in the DIV is refreshed every 10 seconds. This works too.
But what i dream about is that the php page in the DIV is reloaded AFTER the DIV is faded out instead of every 10 seconds. How to do it?
Solved. How it works properly:
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
$(document).ready(function(){
getResult(0);
getResult(1);
getResult(2);
//setInterval("getResult(2)",10000); <== keep this piece of code in case of need.
});
$(document).ready(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
getResult(i);
$els.eq(i).fadeIn();
})
}, 10000)
});

You're already using a callback function after the element has been faded out. So why not call your getResult function inside it?
$el.fadeOut(function(){
// stuff
getResult(i)
})

I have a few suggestions and an example code for you to achieve what you need :
Use $ instead of jQuery for easier reading / writing
$(document).ready is the proper start point for dom related functions
If only one div is visible at a time, do not use too many divs. Most of the time one div is enough for alternating / refreshing content. If there is in/out animation or cross-fading, two divs would be needed. (Example below uses two divs)
Avoid using setInterval except you really really need. Logics with setTimeout better handles unexpected delays such $.post may cause.
start with html code something like this:
...
<div class="top-row-right" style="display:block"></div>
<div class="top-row-right" style="display:none"></div>
...
js:
$(document).ready( function() {
var len = 4; // 'I got X DIV..' This is where we put the value of X.
var template = -1;
function refreshChart() {
template = (template + 1) % len;
$.post("GeochartPerProvince.php?template="+template, function(data) {
var offscreenDiv = ('.top-row-right:hidden');
var onscreenDiv = ('.top-row-right:visible');
offScreenDiv.html(data);
onScreenDiv.fadeOut('slow', function() {
offScreenDiv.fadeIn();
setTimeout(refreshChart, 10000);
});
});
}
refreshChart();
});

Related

Jquery using $this in a for loop in an each loop

Here's my code for a basic jquery image slider. The problem is that I want to have many sliders on one page, where each slider has a different number of images. Each slider has the class .portfolio-img-container and each image .portfolio-img.
Basic html setup is as follows:
<div class="portfolio-item"><div class="portfolio-img-container"><img class="portfolio-img"><img class="portfolio-img"></div></div>
<div class="portfolio-item"><div class="portfolio-img-container"><img class="portfolio-img"><img class="portfolio-img"></div></div>
And javascript:
$.each($('.portfolio-img-container'), function(){
var currentIndex = 0,
images = $(this).children('.portfolio-img'),
imageAmt = images.length;
function cycleImages() {
var image = $(this).children('.portfolio-img').eq(currentIndex);
images.hide();
image.css('display','block');
}
images.click( function() {
currentIndex += 1;
if ( currentIndex > imageAmt -1 ) {
currentIndex = 0;
}
cycleImages();
});
});
My problem comes up in the function cycleImages(). I'm calling this function on a click on any image. However, it's not working: the image gets hidden, but "display: block" isn't applied to any image. I've deduced through using devtools that my problem is with $(this). The variable image keeps coming up undefined. If I change $(this) to simply $('.portfolio-img'), it selects every .portfolio-img in every .portfolio-img-container, which is not what I want. Can anyone suggest a way to select only the portfolio-imgs in the current .portfolio-img-container?
Thanks!
this within cycleImages is the global object (I'm assuming you're not using strict mode) because of the way you've called it.
Probably best to wrap this once, remember it to a variable, and use that, since cycleImages will close over it:
$.each($('.portfolio-img-container'), function() {
var $this = $(this); // ***
var currentIndex = 0,
images = $this.children('.portfolio-img'), // ***
imageAmt = images.length;
function cycleImages() {
var image = $this.children('.portfolio-img').eq(currentIndex); // ***
images.hide();
image.css('display', 'block');
}
images.click(function() {
currentIndex += 1;
if (currentIndex > imageAmt - 1) {
currentIndex = 0;
}
cycleImages();
});
});
Side note:
$.each($('.portfolio-img-container'), function() { /* ... */ });
can more simply and idiomatically be written:
$('.portfolio-img-container').each(function() { /* ... */ });
Side note 2:
In ES2015 and above (which you can use with transpiling today), you could use an arrow function, since arrow functions close over this just like other functions close over variables.
You can't just refer to this inside of an inner function (see this answer for a lot more detailed explanations):
var self = this; // put alias of `this` outside function
function cycleImages() {
// refer to this alias instead inside the function
var image = $(self).children('.portfolio-img').eq(currentIndex);
images.hide();
image.css('display','block');
}

Javascript is not running

This javascript code is supposed to switch when clicked an image to images from a folder within the html file folder.
After it gets to the last image, if you click again it resets to the first image.
Also there's a fade in and out effect on the appearing images.
It doesn't work and I suspect I wrote the path files to the images wrong somehow and the .attr doesn't change the src of the first image to the others.
Things to keep in mind = an extremely beginner programmer, just picked up html and css in about 2 days, I would appreciate any kind of help!
This is the code:
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum])";
//$(indexNum).css("height=600px,width=1000px")
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
)};
)};
)};
You got a couple of errors in your code,
You swapped the closing ")" and "}" in the last two lines and you have a random " in the code.
Here's a working example:
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
indexNum = (indexNum + 1) % imageName.length; // this will count 0,1,2,0,1,2,0,1,2... always looping through your images
$(this).fadeOut(function() { //in this context, this refers to the #head, reading it from the DOM over and over again isn't efficient
$(this).attr("src", imageName[indexNum]);
}).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="head1" src="http://placehold.it/200x200" alt="">
Just a small note: Your script (and mine) don't take into account loading times, this means that it will probably work fine on your computer, locally, but once you put it on a server, you will see the image fadeout, then fadein and still be the same image and then swap to the new image all of a sudden. This happens because it has some loading time. If you want to fix this you'll need some other events. Or you could load all images into the page and then just swap the one that is currently shown.
Even thought this has been answered, here is a fiddle with your original code corrected. http://jsfiddle.net/goqz3coj/
Its better to see how your code should work instead of been giving a different code
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
});
});
});
SECOND VERSION Waits for image load before showing again...
http://jsfiddle.net/goqz3coj/2/
By simply using .load you can wait for the image to load and then show.
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$( "#head1" ).load(function() {
$("#head1").fadeIn(500);
// Handler for .load() called.
});
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
});
});
});
Jonas Grumann took your image urls as easier to show with actual images.

setTimeout not working, other methods of queuing in a for loop?

Code below (the divs are shaded in my real example, I want to sequentially decrease their opacity to 0 so each disappears, in order.
I tried to doing this without using setTimeout, but all of the divs disappeared simultaneously - its good to know that the part of the code that changes the opacity works, but I cant seem to get them to work sequentially.
When I try to use setTimeout (which I presume I am implementing incorrectly),nothing happens!
Any help would be really appreciated with this, I'm fairly new to JavaScript and haven't touched it in a while and tutorials haven't been able to help me.
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<script type="text/javascript">
// the divs that we want to cycle through are named here.
var divs = ["#div1", "#div2", "#div3", "#div4"];
var divsLength = divs.length;
for (var i = 0; i < divsLength; i++) {
setTimeout(function(){
$(divs[i]).fadeTo(1000, 0, function() {
});
},1500);
};
</script>
</body>
Here's a way you should be able to do this without setTimeout:
function doFade(items, index) {
$(items[index]).fadeTo(1000, 0, function() {
doFade(items, index + 1);
});
}
doFade(divs, 0);
If you're targetting browsers that support ES5 (most modern versions do), then you can further simplify doFade:
function doFade(items, index) {
$(items[index]).fadeTo(1000, 0, doFade.bind(this, items, index + 1));
}
working jsfiddle
You can use a recursive function to do that kind of thing, something like that :
function seqFade($el){
$el.first().fadeOut(500, function(){ //Take the first element and fade it out
seqFade($el.slice(1)); //Recall the function when complete with the same set of element minus the first one.
})
}
seqFade($('div')); //Call the function
http://jsfiddle.net/L2fvdfy2/
In your code, it could look like that :
function seqFade($el){
$el.first().fadeOut(500, function(){
seqFade($el.slice(1));
})
}
seqFade($('#div1, #div2, #div3, #div4'));
It's because when the timeout finally fires the variable "i" only has the last index value. Also the loop will start all the timeouts at almost the same time.
There are other ways to accomplish it but this might work with minimal changes to your code.
Try this:
<script type="text/javascript">
var divs = ["#div1", "#div2", "#div3", "#div4"];
var divsLength = divs.length;
for (var i = 0; i < divsLength; i++) {
setTimeout((function(index) {
return function(){
$(divs[index]).fadeTo(1000, 0, function() { });
}
)(i)),1500 + (i * 1500));
};
</script>
</body>
This will create an instance of the function with it's own copy of the index when it was called. Also increasing the timeout of each timeout will have them execute sequentially.
try this:
// the divs that we want to cycle through are named here.
var divs = ["#div1", "#div2", "#div3", "#div4"];
(function fade(i) {
$(divs[i]).fadeTo(1000, 0, function() {
setTimeout(function() {fade(++i);}, 500);
});
})(0);
for (var i = 1; i <= divsLength; i++) {
setTimeout(function(){
$(divs[i]).fadeTo(1000, 0, function() {
});
},1000*i);
lets try this

a setInterval within a for loop in Javascript

My code below needs to put in a setInterval within a for loop. I basically need to put in a 10 second pause between the next iteration of the for loop. This is for a very basic script which shows banners in a div for 10 seconds before moving onto the next one. It existing setInterval is code I got off another website as I ran out of options. Any help? And if you don't mind explaining the logic to me so that I know for the future :)
$("document").ready(function() {
// bannerChange
function bannerChange(banner,div,milliseconds) {
var length = banner.length;
for(i=0;i<length;i++) {
(function(i) {
setInterval(function() {
var url = banners[i].url;
var img = banners[i].image;
$("#"+div).html("<a href='"+url+"' target='_Blank'><img src='www/images/banners/"+img+"' /></a>");
},milliseconds)
})(i);
}
}
function showBanner(bannerName, bannerDiv, milliseconds) {
var url = "www/scripts/ajax/getBanners.php";
$.post(url, {name: bannerName}, function(data) {
if(data.response == true) {
bannerChange(data.banners,bannerDiv,milliseconds);
}
});
}
// Run banners
showBanner("Test Banner","test",10000);
});
Here's an updated version based on the comment:
// Start by getting the banners:
var banners = [];
var currentBanner;
function getBannersFromServer(...) {
// TODO: make ajax call to server for banners
// push the banners into a queue for later
for (var i in bannerFromServer) {
banners.push(bannersFromServer[i]);
}
}
// Then run through them:
function showNextBanner() {
// advance to next banner
currentBanner++
// go back to the beginning after the last banner is displayed
if(currentBanner >= banners.length) currentBanner = 0;
// pull a banner out of the queue
var banner = banners[currentBanner];
// TODO: Show the banner in the div
// do it again in 10 seconds
showNextBanner();
}
// start it all
getBannersFromServer();
getNextBanner();
Try using:
.delay()
Here is a great example of this function in use!
Try this
var i=0;//Global Variable
function bannerChange(banner, div, milliseconds) {
var length = banner.length;
setInterval(function() {
var url = banners[i].url;
var img = banners[i].image;
$("#"+div).html("<a href='"+url+"' target='_Blank'><img src='www/images/banners/"+img+"' /></a>");
i++;
if(i >= length) i=0;//To reiterate from first
},milliseconds);
}
Hope this solves your problem.

Help with JQuery Callback

As per my previous question, I have a working animation which fades in and out each element within the div slideshow. The problem is that I want this animation to continue from the beginning once it has reached the last element. I figured that was easy and that I'd just place an infinite loop inside my JQuery function, but for some reason if I insert an infinite loop, no animation displays and the page hangs. I also cannot find anything in the documentation about how properly place a callback. How can I get this code to restart from the beginning of the animation once it finishes iterating over each object and why is an infinite loop not the right way to go about this?
<div id="slideshow">
<p>Text1</p>
<p>Text2</p>
<p>Test3</p>
<p>Text4</p>
</div>
<script>
$(document).ready(function() {
var delay = 0;
$('#slideshow p').each(
function (index, item)
{
$(this).delay(delay).fadeIn('slow').delay(800).fadeOut('slow');
delay += 2200;
}
);
});
</script>
You could do something like this:
$(function() {
var d = 2200;
function loopMe() {
var c = $('#slideshow p').each(function (i) {
$(this).delay(d*i).fadeIn('slow').delay(800).fadeOut('slow');
}).length;
setTimeout(loopMe, c * d);
}
loopMe();
});
You can give it a try here.
Instead of keeping up with a delay, you can just multiple it by the current index in the loop...since the first index is 0, the first one won't be delayed at all, then 2200ms times the amount of elements later, do the loop again. In the above code d is the delay, so it's easily adjustable, and c is the count of elements.
This solution is in my opinion more elegant, also more natural, it is easier to control, to correctly edit values of delays etc. I hope you'll like it.
$(document).ready(function () {
var elementsList = $('#slideshow p');
function animationFactory(i) {
var element = $(elementsList[i % elementsList.length]);
return function () {
element.delay(200).fadeIn('slow').delay(800).fadeOut('slow', animationFactory(i + 1));
};
}
animationFactory(0)();
});

Categories

Resources