Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect mouseenter direction on a specific element

I currently have a function which detects the direction of the mouse enter. It returns an integer (0-3) for each section as illustrated below.

Example 1

I'm trying to figure out how to alter this function to produce an output based on this illustration:

Example 2

Basically, I just want to figure out if the user is entering the image from the left or the right. I've had a few attempts at trial and error, but I'm not very good at this type of math.

I've set up a JSFiddle with a console output as an example.

The function to determine direction is:

function determineDirection($el, pos){
    var w = $el.width(),
        h = $el.height(),
        x = (pos.x - $el.offset().left - (w/2)) * (w > h ? (h/w) : 1),
        y = (pos.y - $el.offset().top  - (h/2)) * (h > w ? (w/h) : 1);

    return Math.round((((Math.atan2(y,x) * (180/Math.PI)) + 180)) / 90 + 3) % 4;
}

Where pos is an object: {x: e.pageX, y: e.pageY}, and $el is the jQuery object containing the target element.

like image 671
ahren Avatar asked May 20 '13 13:05

ahren


1 Answers

Replace return Math.round((((Math.atan2(y,x) * (180/Math.PI)) + 180)) / 90 + 3) % 4; with return (x > 0 ? 0 : 1);

Another option which I like better (simpler idea):

function determineDirection($el, pos){
    var w = $el.width(),
        middle = $el.offset().left + w/2;        
    return (pos.x > middle ? 0 : 1);
}
like image 75
Tomer Arazy Avatar answered Nov 15 '22 14:11

Tomer Arazy