How to stop Mouseleave from triggering on elements that appear over target?
Asked Answered
W

1

8

jQuery's mouseleave seems to trigger on any covering elements. I don't want these covering elements to be considered as "outside" my target area. Here's a simple example using the datepicker from jQueryUI:

http://jsfiddle.net/6Wm9L/

$("#datepicker").datepicker({});

$(".wrapper")
.mouseenter(function(){
    $("#status").html("Status: Mouse is INSIDE");
})
.mouseleave(function(){
    $("#status").html("Status: Mouse is OUTSIDE");
});

Notice that the mouseleave is triggered when the mouse is over the datepicker. What's a good solution to prevent this for this datepicker example? And what's a good solution for any future elements I might add that cover the target?

Warthman answered 17/6, 2014 at 17:29 Comment(4)
The issue here is that the datepicker popup is absolutely positioned, and as such is not a child of the .wrapper element. Therefore any mouse activity on it will not be bubbled up to .wrapper. A workaround would be to check the mouse co-ordinates against the known boundaries of the .wrapper element, although this will be ugly. Someone else may know of a better solution.Argumentative
The datepicker is appended outside your wrapper.That is the reason.Killdeer
This is an alternative to the co-ords method I mentioned, but will be very easily broken in jQUI changes its' class names: jsfiddle.net/6Wm9L/2Argumentative
Check this jsfiddle.net/6Wm9L/4 : A workaround for it.Killdeer
S
7

You could use the relatedTarget event's property to filter your handler:

.mouseleave(function(e){
    if($(e.relatedTarget).closest('.ui-datepicker').length) return;
    $("#status").html("Status: Mouse is OUTSIDE");
});

--DEMO--

Spendable answered 17/6, 2014 at 17:38 Comment(3)
very nice, I was attempting to find something with isTarget, but this seems to do the trick!Slade
Very nice solution. This would be a worthwhile addition to jQuery core events. I've not used the relatedTarget property before time to do some reading on MDN :)Argumentative
Ah, since the relatedTarget is the other element involved in the event then I can just include a list of classes here that relate to covering elements that I don't want to be considered as "outside". Love it!Warthman

© 2022 - 2024 — McMap. All rights reserved.