0

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?

6
  • 3
    All the delays and fades fire at the same time overwriting everything with the last value only Commented 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? Commented Aug 1, 2015 at 12:01
  • 2
    jsfiddle.net/tc1q1vv7 (jsfiddle.net/tc1q1vv7/1) Commented Aug 1, 2015 at 12:09
  • @adeneo how do i fire them consecutively? Commented Aug 1, 2015 at 12:09
  • @JaredFarrish Thanks! If you include it as an answer, I'll accept it! Commented Aug 1, 2015 at 12:10

1 Answer 1

2

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);
    }
})();

http://jsfiddle.net/tc1q1vv7/1/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.