Shpigford
Shpigford

Reputation: 25338

jQuery: Delayed fade unless clicked?

So I currently I have this:

$('#message_notice').click(function(){
   $(this).fadeOut('slow'); 
});

$('#message_notice').delay(8000).fadeOut('slow');

What I'm ultimately trying to do is if a message is clicked, then go ahead and fade it out. Otherwise, in X seconds, fade it out automatically.

I can do one or the other, but if I have both (as in my example) then the on-click doesn't work (just the delayed fade).

I'm using jQuery 1.4.4.

Upvotes: 2

Views: 311

Answers (2)

SLaks
SLaks

Reputation: 887365

You need to call .stop(true) in the click handler to cancel the delay() that you put in the queue.

New code should look like

$('#message_notice').click(function(){
    $(this).stop(true).fadeOut('slow'); 
});

$('#message_notice').delay(8000).fadeOut('slow');

Upvotes: 5

rsp
rsp

Reputation: 111316

That's because when you run

$('#message_notice').delay(8000).fadeOut('slow');

you are creating an animation queue to which your

$('#message_notice').fadeOut('slow');

gets appended if someone clicks.

For a solution see the answer by SLaks who posted it faster than I could finish writing...

Upvotes: 2

Related Questions