Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Fadeout on Click or after delay

I am displaying a message box on a website. I would like to be able to have it either fadeout on click or after X seconds. The problem is that the delay() function takes the place over the click() function making it so even if you click close you still have to wait the time.

Here is the jQuery

$(document).ready(function() {    
$(".close-green").click(function () {
        $("#message-green").fadeOut("slow");
    });

    //fade out in 5 seconds if not closed
    $("#message-green").delay(5000).fadeOut("slow");

})

I also set up a simple jsfiddle. To see the problem comment out the delay line http://jsfiddle.net/BandonRandon/VRYBk/1/

like image 362
Brooke. Avatar asked Mar 17 '11 21:03

Brooke.


1 Answers

You should change it to a setTimeout: http://jsfiddle.net/VRYBk/3/

(in the jsfiddle link) I removed your delay line and replaced it with a standard setTimeout like:

setTimeout(function(){
    $("#message-green").fadeOut("slow");
},5000)

As a note of WHY, is because JS is read top to bottom and it'll read your delay before you click and trigger the event. Therefore, even when you click the delay is being run causing all animation to pause.

like image 125
Oscar Godson Avatar answered Oct 21 '22 20:10

Oscar Godson