Search code examples
javascriptdelaymouseout

jQuery mouseout and setTimeout


I have the following code.

$("#login").mouseout(function() {
    setTimeout(function() {
        $("#login").animate({
            height: "toggle"
        })
    }, 500);
});

When the mouse leaves #login it will wait 500 ms and then it will hide the element. What I want is that if the mouse leaves the element and get back there in 500 ms it wont hide the element. Otherwise if the mouse has been out of the "range" of the element more than 500 ms, it will call the animate function and hide the element.

If I put this code there

$("#login").mouseover(function() {
    clearTimeout(t);
});

and I take the mouse over the element when it's closing it will pop out again after the animation is completed.


Solution

  • Declare a variable for setTimeout, so that you can use clearTimeout:
    (Plus solved your "it'll pop up again" problem)

    $("#login")
        .mouseout(function() {
            window.t = setTimeout(function() {
                $("#login").animate({
                    height: "toggle"
                })
            }, 500);
        })
        .mouseover(function(){
            if(window.t){
                clearTimeout(window.t);
                window.t = undefined;
            }else{
                //Do your menu popup thing here
            }
        });