Search code examples
javascriptjquerytimeoutaddclassremoveclass

How to addclass with timeout


Don't know why it's not working, i think the code is fine - could you tell me what is wrong? I need to add some class after some time interval...

$('.main_menu ul li').mouseenter(function(){
    setTimeout(function(){
        $(this).children('.sub_menu_main').addClass('opened')
    },200);
});
$('.main_menu ul li').mouseleave(function(){
    $(this).children('.sub_menu_main').removeClass('opened')
});

Solution

  • $('.main_menu ul li').on({
        mouseenter: function(){
            var self = this; //in scope
            $(self).data('timer', setTimeout(function(){ //new scope
                $(self).children('.sub_menu_main').addClass('opened'); //out of scope
            },200);
        },
        mouseleave: function(){
            clearTimeout($(this).data('timer'));
            $(this).children('.sub_menu_main').removeClass('opened');
        }
    });