How to trigger jQuery-UI effect only once on mouseenter?
$('#menu a').hover(
function() {
$(this).css({
'background-color': 'white',
'color': 'black',
}).effect('slide'); // EFFECT
}, function() {
$(this).css({
'background': 'none',
'color': 'white',
});
});
It keeps running forever while mouse is over.
The problem is the slide effect being used because the <a>
slides in from the left and gets a second .hover()
event. I use the fact that the element gains position:relative
from jQueryUI when it is animating to determine whether to add the effect or not.
Adding the CSS
#menu a:hover {
background-color:white;
color:black;
}
and simply using .mouseenter()
$('#menu a').mouseenter(function() {
var $this = $(this);
if ($this.css('position') === 'relative') return;
$(this).effect('slide'); // EFFECT
});
seems to solve it for me.
Edit: So thanks to Matthew in the comments for pointing out that when hovering on the far right, the event still fires multiple times. So here is an updated answer. It uses the newer jQuery .on()
syntax but you could still use the older methods to achieve the same result. It now uses two events, one on the anchors to add the hover style and effect but only if when entering the anchor, the element does not already have the class. I also remove the hover class from all other anchors when hovering an anchor. The second event covers the removal of the hover class when exiting the whole menu. Without this second event the last anchor hovered when moving away from the menu is left with the .hover
class.
JavaScript
var $anchors = $('#menu a');
$('#menu').on('mouseenter', 'a', function() {
$anchors.not(this).removeClass('hover');
var $this = $(this);
if ($this.hasClass('hover')) return;
$this.addClass('hover').effect('slide'); // EFFECT
});
$('#menu').on('mouseleave', function() {
$anchors.removeClass('hover');
});
CSS
#menu {
background-color: black;
}
#menu a {
display: block;
color: white;
}
#menu a.hover {
background-color:white;
color:black;
}
HTML
<div id="menu">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
Hope this helps.