Let me describe the problem in details:
I want to show an absolute positioned div when hovering over an element. That's really simple with jQuery and works just fine. But when the mouse goes over one of the child elements, it triggers the mouseout event of the containing div. How do I keep javascript from triggering the mouseout event of the containing element when hovering a child element.
What's the best and shortest way to do that with jQuery?
Here is a simplified example to illustrate what I mean:
Html:
<a>Hover Me</a> <div> <input>Test</input> <select> <option>Option 1</option> <option>Option 2</option> </select> </div>
Javascript/jQuery:
$('a').hover( function() { $(this).next().show() } function() { $(this).next().hide() } );
The mouseout event is fired at an Element when a pointing device (usually a mouse) is used to move the cursor so that it is no longer contained within the element or one of its children.
This means that mouseleave is fired when the pointer has exited the element and all of its descendants, whereas mouseout is fired when the pointer leaves the element or leaves one of the element's descendants (even if the pointer is still within the element).
For mouseout the reverse: event. target – is the element that the mouse left.
The mouseover event triggers when the mouse pointer enters the div element, and its child elements. The mouseenter event is only triggered when the mouse pointer enters the div element. The onmousemove event triggers every time the mouse pointer is moved over the div element.
The question is a bit old, but I ran into this the other day.
The simplest way to do this with recent versions of jQuery is to use the mouseenter
and mouseleave
events rather than mouseover
and mouseout
.
You can test the behavior quickly with:
$(".myClass").on( { 'mouseenter':function() { console.log("enter"); }, 'mouseleave':function() { console.log("leave"); } });
For simplicity sake, I would just reorganize the html a bit to put the newly displayed content inside the element that the mouseover event is bound to:
<div id="hoverable"> <a>Hover Me</a> <div style="display:none;"> <input>Test</input> <select> <option>Option 1</option> <option>Option 2</option> </select> </div> </div>
Then, you could do something like this:
$('#hoverable').hover( function() { $(this).find("div").show(); }, function() { $(this).find("div").hide(); } );
Note: I don't recommend inline css, but it was done to make the example easier to digest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With