Can I delay jQuery addClass?
Asked Answered
S

5

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().

Steeve answered 29/1, 2011 at 9:50 Comment(0)
U
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');
});
Unbounded answered 29/1, 2011 at 9:54 Comment(2)
You haven't replaced the non-functional call to delay.Painterly
@lonesomeday: That shouldn't matter in the code but thanks done :)Unbounded
P
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?

Phraseologist answered 26/2, 2013 at 8:37 Comment(0)
U
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');
});
Unbounded answered 29/1, 2011 at 9:54 Comment(2)
You haven't replaced the non-functional call to delay.Painterly
@lonesomeday: That shouldn't matter in the code but thanks done :)Unbounded
P
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.

Painterly answered 29/1, 2011 at 9:54 Comment(0)
M
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;
}
Matherne answered 8/6, 2017 at 19:53 Comment(0)
F
0

You should use callbacks .

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

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

Flamsteed answered 29/1, 2011 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.