One problem with the standard mouseout
event is that it fires not only when the cursor leaves the region of the screen bounded by the element's external perimeter, but also when the cursor hovers over some other element contained within this perimeter.
The rationale for jQuery's mouseleave
event is to signal only the moment when the cursor leaves the the area bounded by an element's external perimeter.
Unfortunately, this seems to work only if the "obstructing" element is a descendant of the "obstructed" element. If the "obstructing" element is where it is through absolute positioning, then when the mouse hovers over it, the mouseleave
event on the "obstructed" element gets fired.
For example, with the following HTML:
<div id="b-div">
<div id="d-div"><span>d</span></div>
</div>
<div id="c-div"><span>c</span></div>
...#d-div
is a bona-fide descendant of #b-div
, whereas #c-div
isn't, but, but we can style it so that it "obstructs" #b-div
all the same. This is illustrated in this jsFiddle.
If now one defines the following events on #b-div
:
$( '#b-div' ).bind( {
mouseenter: function () {
$( this ).addClass( 'outlined' );
},
mouseleave: function () {
$( this ).removeClass( 'outlined' );
}
} );
...then hovering the mouse within #b-div
's outer perimeter causes a blue outline to appear over this perimeter, unless the mouse is over #c-div
.
Is there a way to get the same effect with #b-div
and #c-div
as mouseleave
achieves with #b-div
and #d-div
?
EDIT: I've fixed the example shown in the jsFiddle. The original version of this example showed the unrepresentative special case in which all of the obstructing element overlaps with the obstructed element. In this special case, the desired effect can be simulated by defining the same events on both the obstructing and the obstructed elements, thus, in effect, turning the obstructing element into a patch of the obstructed element. This won't work when the obstructing element is not fully contained within the obstructed element's outer perimeter (as shown in the amended jsFiddle). More generally, any solution that is based on using a mouseover
event on the obstructing element is bound to fail, since the real problem is to prevent (or render ineffective) the spurious mouseleave
on the obstructed element.
e.relatedTarget
jsfiddle.net/p5yf0dcs/2 The problem is that you now won't lose the highlight when mousing out of theb-div
– Punner#b-div
to get the class unless it's under the mouse. In your example, it gets the class when you mouse over any part of#c-div
. – Kenyakenyatta