11

Is there a way to delay the addClass() of jQuery? For example this code

$('#sampleID').delay(2000).fadeOut(500).delay(2000).addClass('aNewClass');

When I load the page, it has the class 'aNewClass' already on id 'sampleID'. How to solve this problem? What I want is the addClass will happen after it ended the fadeOut().

Ryan
  • 1,783
  • 8
  • 27
  • 42

5 Answers5

21

You can't directly delay an addClass call, however you can if you wrap it in a queue call which takes a function as a parameter like this

$(this).delay(2000).queue(function(){$(this).addClass('aNewClass')});

See this post: jQuery: Can I call delay() between addClass() and such?

Community
  • 1
  • 1
Dave
  • 1,409
  • 2
  • 18
  • 14
12

What I want is the addClass will happen after it ended the fadeOut().

You can use callback function to fadeOut like this:

$('#sampleID').fadeOut(500, function(){
  $(this).addClass('aNewClass');
});
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

You can also use setTimeout, with CSS transition :

setTimeout(function() {
    $('#sampleID').addClass('aNewClass');
}, 2000);

And the CSS

#sampleID {
transition: opacity 1s ease;
opacity: 0;
}

#sampleID.aNewClass {
opacity: 1;
}
brandozz
  • 1,059
  • 6
  • 20
  • 38
1

You can't do this with delay because it only affects the effects queue. It doesn't "pause" execution of later code if it is not implemented using the queue.

You need to do this with setTimeout:

$('#sampleID').delay(2000).fadeOut(500, function() {
    setTimeout(function() {
        $(this).addClass('aNewClass');
    }, 2000);
});

This uses the complete callback of fadeOut and then sets a function to execute 2 seconds in the future.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0

You should use callbacks .

$('#sampleID').delay(2000).fadeOut(500,function(){
   $(this).delay(2000).addClass('aNewClass');
});

http://api.jquery.com/fadeOut/

Arshdeep
  • 4,281
  • 7
  • 31
  • 46