Search code examples
jquerytimeoutdelaydrop-down-menu

Adding delay to jquery drop down menu


I'm trying to add delay to a simple drop down menu. With the following code I get a delay but wrong kind. When I move my mouse over the menu really fast, it delays it but still opens it after the 300ms. The right behavior would be to open the menu when the mouse has hovered 300ms on it, same when leaving it.

$('#menu-item-1226:not(.parent-pageid-1225 #menu-item-1226)').hover(function(){
    var menu = this;
    setTimeout(function(){
        $(menu).find('ul').slideToggle(100);
    }, 300);
});

Do I have to stop it somehow or what is the right approach here?
Thanks in advance


Solution

  • This is probably what you are looking for, however using the Jquery Plugin HoverIntent will work as well, and maybe even better.

    without hover intent:

    $(function() {
            var timer;
        $('#Header li').hover(function(){
                    if(timer) {
                            clearTimeout(timer);
                            timer = null
                    }
                    timer = setTimeout(function() {
                               $(this).find('ul').slideToggle(100);
                    }, 500)
        },
        // mouse out
        });
    

    });

    with hover intent plugin

    $("#Header li").hoverIntent({
        sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
        interval: 50,   // number = milliseconds of polling interval
        over: function () {
            $('ul', this).slideDown(220);
        },  // function = onMouseOver callback (required)
        timeout: 0,   // number = milliseconds delay before onMouseOut function call
        out: function () {
            $('ul', this).hide();
        }    // function = onMouseOut callback (required)
    });