Search code examples
jquerycssdelaysequencefadeout

.delay() not behaving as expected


I'm sure there's a simple solution to this problem, but I can't find it.

I have created a function that makes lines of text fade out sequentially, one by one, calling the .fadeOut() method on .each() element within an array.

However, when I run exactly the same code, but with the .css() method (to turn the text red), it changes them all at once, and not sequentially as above.

Can anyone explain why this is?

https://jsfiddle.net/v9hzpuf6/3/

Thanks in advance

EDIT Including code here:

<h1>Example 1: .fadeOut()</h1>
<h2>Works as expected...</h2>
<p class="top">line 1</p>
<p class="top">line 2</p>
<p class="top">line 3</p>
<button class="ex1">"Go"</button>

<h1>Example 2: .css()</h1>
<h2>Doesn't work as expected...</h2>
<p class="bottom">line 1</p>
<p class="bottom">line 2</p>
<p class="bottom">line 3</p>
<button class="ex2">Go</button>

JS:

$("button.ex1").on("click", function() {
  $(".top").each(function(index) {
    $(this).delay(400 * index).fadeOut();
  });
});

$("button.ex2").on("click", function() {
  $(".bottom").each(function(index) {
    $(this).delay(400 * index).css("color", "red");
  });
});

Solution

  • delay() only affects the various queues jQuery maintains, which css() does not use. To achieve the effect for the css() method you could use setInterval(). Try this:

    $("button.ex2").on("click", function() {
        var index = 0;
        var timer = setInterval(function() {
            var $next = $('.bottom').eq(index++);
            if (!$next.length)
                clearInterval(timer);
            else
                $next.css('color', 'red');
        }, 400);
    });
    

    Updated fiddle