Reputation: 1
I have some code that works, but sometimes it just "jumps" to the other text without respecting the interval.
The code basically changes a header's text on an interval.
var text = ["text1", "text2", "text3","text4","text5"];
var index = 0;
$("#description").fadeOut("slow");
setInterval(function(){
$("#description").html(text[index]).fadeIn("slow");
$("#description").delay(400).fadeOut("slow");
index++;
if (index == 5) {
index = 0;
};
}, 1800);
If you guys can help me make this work,or even improve it I would be very thankful :)
Fiddle: http://jsfiddle.net/erbfqqxb/
Upvotes: 0
Views: 206
Reputation: 77
<pre>Use call back function and remove delay</pre>
JSFIDDLE: http://jsfiddle.net/rajen_ranjith/erbfqqxb/3/.
Upvotes: 0
Reputation: 58422
I think the problem may be caused when your interval catches up to the time taken for your delays and fades. Try running each animation in the callback so that it is run as a linear process to keep the text from "jumping":
var text = ["text1", "text2", "text3","text4","text5"];
var index = 0;
var description = $("#description");
description.fadeOut("slow", changeText);
function changeText(){
// run the initial animation
description.html(text[index]).fadeIn("slow", function() {
// run the second animation after the first one has finished - can remove the delay if you want to
// the delay here is how long you want the text to be visible for before it starts to fade out
description.delay(400).fadeOut("slow", function() {
index++;
//measure against array length instead of hard coded length
if (index == text.length) {
index = 0;
};
//set the delay before restarting animation sequence (only restart once the sequence has finished)
setTimeout(changeText, 400);
});
});
}
Upvotes: 2
Reputation: 110
Here is the working code and its more dynamic by using
index == text.length
$(function() {
var text = ["text1", "text2", "text3","text4","text5"];
var index = 0;
$("#description").fadeOut();
setInterval(function(){
$("#description").html(text[index]).fadeIn("slow");
$("#description").delay(400).fadeOut("slow");
index++;
if (index == text.length) {
index = 0;
};
},1800);
});
Upvotes: 0
Reputation: 29683
Just try as below:
setInterval(function(){
//first stop what you are doing and then fadeIn again
$("#description").stop().html(text[index]).fadeIn("slow",function(){
//set a callback to do all these things once fadeIn is completed
index++;
$("#description").delay(400).fadeOut("slow");
if (index == 5) {
index = 0;
};
});
},1800);
I think the problem was with delay
. setInterval
time and delay time
were conflicting. So the above approach seems better to me.
Upvotes: 1
Reputation: 605
I think this happen due to the line
$("#description").fadeOut("slow");
comment that line it will work fine.
Upvotes: 0