9

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.

ahren
  • 16,803
  • 5
  • 50
  • 70

1 Answers1

5

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);
}
Tomer Arazy
  • 1,833
  • 10
  • 15
  • 1
    Wow, that's embarrassingly simple (I will accept as soon as I can). Here's the JSFiddle link for others: http://jsfiddle.net/aBK5Q/2/ – ahren May 20 '13 at 13:48
  • 4
    Just a little nitpicky comment: you are still not really able to determine the directon of the mouseenter movement. You just determine in what half of your graphic your cursor first arrives. So, if you move your mouse fast, you can enter the graphic from the left but end up in the right half. If you want to handle that behaviour, you would probably need to save your mouse coordinates on every mousemove and compare your last coordinates to the coordinates right after the mouseenter event. But I think the above answer works just fine for probably any real life cases. – basilikum May 20 '13 at 14:00