Phil
Phil

Reputation: 1662

Why doesn't my jQuery delay() function work correctly?

I have some jQuery and am trying to apply a delay to it but can't seem to get it to work:

image.css({"visibility" : "hidden"}).removeClass("image-background");

and I have tried amending this according to the jQuery website (http://api.jquery.com/delay/) to apply the delay:

image.delay(800).css({"visibility" : "hidden"}).removeClass("image-background");

but this doesn't seem to make any difference.

Can anyone see a problem with this? Or how I could fix the problem?

Upvotes: 20

Views: 38589

Answers (2)

RightSaidFred
RightSaidFred

Reputation: 11327

.delay() is not only for animations. It's for anything in a queue.

image.delay(800)
     .queue(function( nxt ) {
         $(this).css({"visibility":"hidden"}).removeClass("image-background");
         nxt(); // continue the queue
     });

Here's a JSFiddle demo

Upvotes: 35

Rory McCrossan
Rory McCrossan

Reputation: 337560

The delay() function only applies to actions queued on the element. Most commonly, but not always, these are actions created by the animate() method. In this case, use setTimeout to run some code after a specified interval.

Try this:

setTimeout(function() {
    image.css({"visibility" : "hidden"}).removeClass("image-background");
}, 800);

Upvotes: 42

Related Questions