javascriptjqueryhoverintent

How to use $.hoverIntent and setTimeout together?


I am using hoverIntent plugin for my horizontal drop down navigation menu as I want few millisecond delay before opening the submenu associated with current main menu. Also I have a requirement that opened menu should not get closed immediately as and when user moves mouse pointer away from currently opened menu.

Fiddle link: https://jsfiddle.net/vijayP/tbg2x5h7/6/

So I have come up with following code:

    $(document).ready(function(){

    var config = {
            over: function () {
                $(this).addClass("show");
            }, 
            timeout: 300, 
            out: function () {
                var _this = $(this);
                setTimeout(function () {
                    $(_this).removeClass("show");
                }, 300);

            }
        };
    $("ul.drop_menu li").hoverIntent(config);
});

Here menu is getting opened (adding show class) after 300 millsec. And on hover out; 300 millisec delay have been added to avoid sudden close of menu. This code works fine with no issue. The problem I am observing is:

Problem: If user moves away from menu then I want 300 millisec delay before closing the submenu. But if user moves cursor from 1st main menu to 2nd main menu; then I want to close 1st submenu immediately and don't want to show 2 submenu overlapped to each other. In fiddle you can see this overlapping effect when you are on 1st main menu and goes to 2nd main menu.


Solution

  • When you hover over an li element, you can just remove the show class from siblings. See the updated jsfiddle https://jsfiddle.net/tbg2x5h7/7/

    $(document).ready(function(){
    
        var config = {
                over: function () {
                    $(this).siblings().removeClass("show");
                    $(this).addClass("show");
                }, 
                timeout: 300, 
                out: function () {
                    var _this = $(this);
                    setTimeout(function () {
                        $(_this).removeClass("show");
                    }, 300);
    
                }
            };
        $("ul.drop_menu li").hoverIntent(config);
    });