Jquery hover and setTimeout / clearTimeOut

I am currently trying to make a menu with a submenu. Here is what I want to do.

When hovering a link (#mylink), I want to display a div (lets call it "#submenu") right below it. Leave this link on the mouse; you want to execute the function in 5 seconds.

In this interval, 5 seconds, if I find my div (#submenu), I want clearTimeout. So this div will not fade after 5 seconds.

Here is my code:

$(document).ready(function()
{
    $("#mylink").hover(
        function ()
        {
            $('#submenu').show();
        },
        function()
        {
            var timer = setTimeout(function(){$('#submenu').hide();}, 5000);
        }
    );

    $("#submenu").hover(
        function ()
        {
            clearTimeout(timer);
        },
        function()
        {
            $('#submenu').show();
        }
    );
}
+3
source share
4 answers

SLaks , , , var timer . , timer - , .

$(document).ready(function(){
    var timer;
    $("#mylink").hover(
        function(){
            $('#submenu').show();
        }, function(){
            timer = setTimeout(function(){$('#submenu').hide();}, 5000);
        }
    );

    $("#submenu").hover(
        function(){
            clearTimeout(timer);
        }, function(){
            $('#submenu').show();
        }
    );
}
+11

var timer - .
.

.

+5

This is how i do it

var timer
$("#mylink").mouseenter(function(){clearTimeout(timer);$('#submenu').show()})
$("#mylink").mouseout(function(){timer = setTimeout(function(){$('#submenu').hide();}, 1000);})
+2
source

If you put #submenu inside #mylink, you don’t need a second event handler for #submenu, and you will have something like this:

var timer;
$(document).ready(function()
{
    $('#mylink').hover(function()
    {
        clearTimeout(timer);
        $('#submenu').show();
    },function()
    {
        timer = setTimeout(function(){$('#submenu').hide();},5000);
    });
}

By the way, you do not need jQuery for this. In simple js, it won't take so long to write code.

+1
source

All Articles