Reputation: 3807
i have 3 div elements with class name gridbox
i want to add a class into all 3 elements with delay.
for example:
new class should be added to all 3 div elements with a delay between each of them.
i triel following code which is not working.
$('.gridbox').addClass('animation').delay(1500);
What is wrong here?
Upvotes: 1
Views: 3926
Reputation: 214949
Although setTimeout/Interval kinda "works", jquery provides a much cleaner way to do custom animations: queue
, for example:
$(".gridbox").each(function() {
var box = this;
$("body").queue(function(next) {
$(box).addClass("animation");
next();
}).delay(1000)
});
Upvotes: 0
Reputation: 4387
You can do this without jQuery
function addClass () {
var div = document.getElementsByClassName("aaa");
div[0].className = "bbb";
setTimeout(addClass, 1000);
}
window.onload = function () {
addClass();
}
Upvotes: 0
Reputation: 1524
a nicer solution :)
var st = setInterval(function(){
var gb = $('.gridbox:not(.animation):eq(0)');
gb.length > 0 ? gb.addClass('animation') : clearInterval(st);
},1500)
Upvotes: 0
Reputation: 47956
You could try something like this:
var divs = $( '.gridbox' );
var index = 0;
var delay = setInterval( function(){
if ( index <= divs.length ){
$( divs[ index ] ).addClass( 'animation' );
index += 1;
}else{
clearInterval( delay );
}
}, 1500 );
What I'm doing here is this:
divs
variable.setTimeout
function with a delay of 1.5 seconds.Upvotes: 4
Reputation: 133403
You can try combination of .each() and setTimeout
$('.gridbox').each(function (index) {
var $this = $(this);
setTimeout(function () {
$this.addClass('animation');
}, 1500 * index );
});
Upvotes: 0
Reputation: 712
if you want to apply a delay on a jquery function such as addClass you need to use a javascript setTimeout because as described here .delay()
is limited and should be used for jQuery effects
Upvotes: 0
Reputation: 318182
$('.gridbox').each(function(i) {
(function(self, j) {
setTimeout(function() {
$(self).addClass('animation');
},(j*1500)+1500);
})(this, i);
});
Upvotes: 3
Reputation: 160833
$('.gridbox').each(function(index) {
var that = this;
setTimeout(function() {
$(that).addClass('animation');
}, 1500 * index);
});
Upvotes: 0