Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Pop up message

I am trying to make a custom pop up message, that appears, displays to the user for 5 seconds and then fades out. This works fine BUT if the use triggers the event multiple times and the time out 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

like image 639
Shaun Hogg Avatar asked Jan 04 '13 10:01

Shaun Hogg


1 Answers

Try this:

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 return of setInterval to a variable. This handle can be used to end the interval with clearinterval. (You can't clear a interval by function, only by interval handle)

Also, I pulled the closeBox function out of the showMessage function, it's not necessary to declare it every time showMessage is called.

like image 113
Cerbrus Avatar answered Oct 13 '22 01:10

Cerbrus