Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  15] [ 3]  / answers: 1 / hits: 15607  / 13 Years ago, thu, march 17, 2011, 12:00:00

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/


More From » jquery

 Answers
10

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.


[#93216] Wednesday, March 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
;