JQuery post

I am trying to create a custom pop-up message that appears, displays to the user for 5 seconds, and then disappears. This works fine, but if you use the event trigger several times and the timeout is already running, the message quickly disappears.

My function so far ...

function showMessage(message) { $(".messageText").text(message); $(".message").fadeIn("slow"); closeBox = function(){ $(".message").fadeOut("slow"); } clearInterval(closeBox); setInterval(closeBox, 5000); } 

Many thanks

+7
source share
2 answers

Try the following:

 var interval; function showMessage(message) { $(".messageText").text(message); $(".message").fadeIn("slow"); if(interval){ // If a interval is set. clearInterval(interval); } interval = setInterval(closeBox, 5000); } function closeBox(){ $(".message").fadeOut("slow"); } 

You need to assign the value of the setInterval variable to the variable. This handle can be used to end the interval with clearinterval . (You cannot clear the interval by function, only using the interval descriptor)

In addition, I pulled the closeBox function from the showMessage function, there is no need to declare it every time showMessage is showMessage .

+8
source

How about using jQuery delay?

Example:

 $("#container").fadeIn().delay(amoutOfTimeInMiliseconds).fadeOut(); 

Your function:

 function showMessage(message) { $(".messageText").text(message); $(".message").fadeIn("slow").delay(5000).fadeOut("slow"); } 

It should work ... Regards.

+4
source

All Articles