Reputation: 431
I have a button li
with a nested input
. I added hover function with jQuery to the li
element. It works fine except when I hover in and out of the li
button really quickly, the mouseenter
won't trigger and instead only mouseleave
triggers, even when still hovering on the element.
I know the problem is caused by the timer, but I can't figure out how to set it up to work as intended.
$(document).ready(function() {
$('.topMenu__item--button').hover(function () {
var hoverTimeout;
clearTimeout(hoverTimeout);
$(this).addClass('topMenu__item--button--hover');
}, function() {
var $self = $(this);
hoverTimeout = setTimeout(function() {
$self.removeClass('topMenu__item--button--hover');
}, 500);
});
});
Upvotes: 1
Views: 81
Reputation: 337560
You need to move the hoverTimeout
declaration to be in scope of both functions:
$(document).ready(function() {
var hoverTimeout;
$('.topMenu__item--button').hover(function() {
clearTimeout(hoverTimeout);
$(this).addClass('topMenu__item--button--hover');
}, function() {
var $self = $(this);
hoverTimeout = setTimeout(function() {
$self.removeClass('topMenu__item--button--hover');
}, 500);
});
});
You should also note that it would be better practice to put this hover behaviour in to CSS, as it performs much better than JS.
Upvotes: 1