Reputation: 804
is there a way to know if the mouse event has left from a specific side of the element?I mean, I have a DIV with a mouseover/mouseenter event and I want to trigger the action only if the mouse leaves to the left side of the DIV and to the right, but if it leaves from bottom or top, it shouldn't trigger any action.
Thank you in advance.
Upvotes: 7
Views: 4771
Reputation: 3854
I realise this is an old question, but I was looking for something similar to use for hover effects. I found jquery.hoverdir
Could be handy...
Upvotes: 2
Reputation: 1176
With jQuery you could use the offsetX property of the event as so:
$('#element').mouseout(function(e) {
if (e.offsetX < 0 || e.offsetX > $(this).width()) {
alert('out the side!');
}
});
I don't think that property is reliable cross-browser (w/o jQuery) and I believe jQuery normalizes it (I've tested it in Chrome & IE7-9). Basically, the property contains where the cursor is relative to the target element at the time the event is fired. If the value is less than 0 or greater than the width of the element, you know the cursor was outside the left or right side of the element at the time it left the bounds of the element.
Upvotes: 7
Reputation: 175
Maybe you could use the mouseout jquery function (or mouseleave?) and add a custom handler with javascript to get the co-ordinates of the element, the height and width, and track if the mouse co-ordinates are past your boundary.
i.e. your mouse-out event fires, the handler locates the element at (x, y) -> (10, 10), the height is 20 and the width is 20. If the mouse-co-ordinates are greater than 30 on the X and between 10 and 30 on the Y, the mouse has left on the right hand side.
Upvotes: 1
Reputation: 8834
Not in an easy way, AFAIK, but it can be done.
On mouse out, you compare the mouse position with the element position.
See mouse position tutorial for jQuery: http://docs.jquery.com/Tutorials:Mouse_Position
(it uses mousemove in the tutorial, but it also works for mouseenter/mouseleave)
Upvotes: 1
Reputation: 1075845
You can check the pageX
and pageY
properties of the event object and compare them to the dimensions of the element in question (e.g., from offset
and adding in outerWidth
/ outerHeight
as appropriate).
Upvotes: 5