Search code examples
javascriptjquerydelaymouseentermouseleave

How to delay mouseleave action with jQuery


I have a menu. In this menu I have some hidden submenus, so I'm showing it after hover action. I have also some delay effect on submenus showing. Now I want to add the same effect on hiding it. But it's not working. Also how can I add some delay on hover/mouseenter next menu element?

$('.main_menu ul li').on({
    mouseenter: function(){
        var self = this,
            time = 200;
        $(self).data('timer', setTimeout(function(){
            $(self).children('.sub_menu_main').addClass('opened');
        }, time));
    },
    mouseleave: function(){
        var self = this,
            time = 200;
        clearTimeout($(self).data('timer'));
        setTimeout(function() {
            $(self).children('.sub_menu_main').removeClass('opened');
        }, time);
    }
});

Solution

  • I made good solve for this question, so:

    var timer;
    $('.main_menu ul li').on({
        mouseenter: function(){
            var self = this;
            clearTimeout(timer);
            timer = setTimeout(function(){
                $(self).children('.sub_menu_main').addClass('opened');
            }, 100)
        },
        mouseleave: function(){
            var self = this;
            setTimeout(function(){
                if (!$(self).children('.sub_menu_main').is(":hover")){
                     $(self).children('.sub_menu_main').removeClass('opened');
                }
            }, 100);
        }
    });