Lukas
Lukas

Reputation: 7734

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')
});

Upvotes: 2

Views: 4705

Answers (2)

adeneo
adeneo

Reputation: 318182

$('.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');
    }
});

Upvotes: 5

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

I believe this isn't referencing what you think it does in that scope. You should try storing a reference to this in your outer scope, and then access the hovered element through that reference instead:

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

Upvotes: 2

Related Questions