I am mocking up a simple multi-level drop down box and cannot figure out how to get the hover event to fire only once when a li is hovered. The hover event fires twice when the a tag inside of the list-item is hovered.
Here is a jsFiddle that demonstrates the problem. I’ve added extra padding around the a tag to show how the event is fired twice. If just the padding is hovered, the event will fire once, but once the a tag is hovered, it will fire again.
HTML:
<ul class="dropit">
<li><a href="#">Thing 1</a></li>
<li><a href="#">Thing 2</a></li>
<li><a href="#">Thing 3</a>
<ul>
<li><a href="#">Sub-thing 1</a></li>
<li><a href="#">Sub-thing 2</a>
<ul class='sub-menu'>
<li><a href="#">Sub-sub-thing 1</a></li>
<li><a href="#">Sub-sub-thing 2</a></li>
</ul>
</li>
</ul>
</li>
</ul>
jQuery:
$(document).ready(function(e) {
$('ul.dropit li').on('mouseover', function(event) {
$target = $(event.currentTarget);
$sub = $target.children('ul').first();
$sub.slideToggle();
}).on('mouseout', function(event) {
$target = $(event.currentTarget);
$target.children('ul').first().slideToggle();
});
});
Use
mouseenterandmouseleaveinstead ofmouseoverandmouseoutFIDDLE
mouseoverwill fire when you hover over a child element.mouseenterfires only once no matter how many children are hovered.