yarek
yarek

Reputation: 12064

Jquery : how to add classes in sequence?

I want to create a simple css effect adding classes to items:

https://jsfiddle.net/xjmm2k8n/

<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>

.item {
  opacity:0;
}

$(".item").each(function(index, element) {    
    console.log(element);
    $(element).css('opacity', 1).delay(1000);  
});

So if I have 5 items whose opacity is 0, I want to make the opcaity to 1 each element after another in sequence (1 second of delay)

Any clue ?

Upvotes: 0

Views: 178

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use a setTimeout at this context,

$(".item").each(function(index, element) {    
    setTimeout(function(){ 
       $(element).css('opacity', 1); 
    }, 1000 * index);
});

There is no need to create a scope per iteration, .each() would do that for you. Internally, each would call the passed callBack function by supplying the index and element. That actually creates a scope for you. So it would automatically help us to escape from the problem caused by the closure.

DEMO

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

You need to chain functions. :) You may use .animate or a closure in setTimeout():

time = 0;
$(".item").each(function(index, element) {
    console.log(element);
    (function (e, t) {
      setTimeout(function () {
        $(e).css('opacity', 1);
      }, t);
    })(element, time+=1000);
});

And it works: https://jsfiddle.net/u6e6mxL9/

Upvotes: 1

Related Questions