I'm trying to iterate through an array and assign values to an element as such:
<tool>hammer</tool>
var tools = ["screwdriver", "wrench", "saw"];
var i;
for (i=0; i < tools.length; ++i){
$("tool").delay(300).fadeOut().delay(100).html(tools[i]).fadeIn();
};
However this doesn't seem to work as only "saw" is assigned as the html value and keeps fading in and out.
What am I doing wrong here?
-
3All the delays and fades fire at the same time overwriting everything with the last value onlyadeneo– adeneo2015年08月01日 12:00:07 +00:00Commented Aug 1, 2015 at 12:00
-
@adeneo tool is a custom html element. got it. so if i include them in separate lines it should work?blue_zinc– blue_zinc2015年08月01日 12:01:50 +00:00Commented Aug 1, 2015 at 12:01
-
2jsfiddle.net/tc1q1vv7 (jsfiddle.net/tc1q1vv7/1)Jared Farrish– Jared Farrish2015年08月01日 12:09:12 +00:00Commented Aug 1, 2015 at 12:09
-
@adeneo how do i fire them consecutively?blue_zinc– blue_zinc2015年08月01日 12:09:20 +00:00Commented Aug 1, 2015 at 12:09
-
@JaredFarrish Thanks! If you include it as an answer, I'll accept it!blue_zinc– blue_zinc2015年08月01日 12:10:21 +00:00Commented Aug 1, 2015 at 12:10
1 Answer 1
jQuery.delay() pauses between effects queued items, so your .html() is being set instantaneously. Hence, you only see saw.
A solution is to scrap the for loop and "loop" against the length of the array, setting the tool text to the next first item in the array (as you remove it). However, you need to do this inside the context of the queue, so you can use the .fadeOut() callback to do this.
Wrap all this in a function (here, I immediately invoke it but give it a label, a, so it can be referenced, it's not anonymous) and pass that to .fadeIn() at the end so it continues the loop until the array is empty.
var tools = ["screwdriver", "wrench", "saw"];
(function a(){
if (tools.length) {
$("tool").delay(300).fadeOut(0, function(){
$(this).html(tools.shift());
}).delay(100).fadeIn(a);
}
})();