rob-gordon
rob-gordon

Reputation: 1488

JQuery Hover Function Timeout

I've seen other similar questions to this on SO but the answers weren't quite what I'm looking for. My problem with the code below is about the variable hide.

In it's current form hide won't be visible to the first hover function, but I don't want to declare it at a higher scope because it has no use there. Plus declaring it at a higher scope would require making a different variable for every li.

What's the solution for keeping this variable containing a timeout between these two functions?

$('li').hover(function() {
    clearTimeout(hide);
    $('.menu', this).show();
}, function() {
    var menu = $('.menu', this);
    var hide = setTimeout(function() {
        menu.hide();
    }, 500);
});

Upvotes: 0

Views: 218

Answers (1)

Musa
Musa

Reputation: 97672

You can store the value with .data()

$('li').hover(function() {
    clearTimeout($(this).data('hide'));
    $('.menu', this).show();
}, function() {
    var menu = $('.menu', this);
    $(this).data('hide', setTimeout(function() {
        menu.hide();
    }, 500));
});

Upvotes: 2

Related Questions