Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differ mouseout/leave events by side on jquery?

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.

like image 448
steps Avatar asked Mar 21 '12 18:03

steps


2 Answers

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.

like image 137
robmisio Avatar answered Nov 02 '22 23:11

robmisio


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).

like image 26
T.J. Crowder Avatar answered Nov 02 '22 23:11

T.J. Crowder