How to determine where the mouse is leaving the image

On this page:!/work/

You can see that the image is scrolling to / from the direction the mouse enters and exits. How it's done?


source to share

3 answers

You can get the x / y coordinates of the cursor when the event mouseleave

fires for an element:

$('#my-element').on('mouseleave', function (event) {

    //check to see what quadrant of the element the mouse has left the element
    //you could get a lot more complex than this but here an example to get you going
    if (event.offsetX > 50 && event.offsetY > 50) {
    } else if (event.offsetX > 50 && event.offsetY <= 50) {
    } else if (event.offsetX <= 50 && event.offsetY <= 50) {
    } else {


Here's a demo:



Because of the event mouseout

and properties of screenX

/ screenY

/ clientX

/, clientY

it is possible to calculate the direction with simple trigonometry.



It only responds to vertical and horizontal directions. If you try diagonal images it doesn't work. So based on that, I think you can use an event mousemove

to give you the x and y offsets. If x offset is greater than y, it means the user is moving horizontally and vice versa.



All Articles