MR. A
MR. A

Reputation: 195

How to Detect the Mouse Pointer Come From When Hover Elements

I just want to ask how to detect the mouse pointer come from using jquery when the pointer hover an element like div.

When run the function I want to know mouse pointer come from top, left, bottom and right

Thank you!

Upvotes: 2

Views: 907

Answers (1)

Ethan
Ethan

Reputation: 4375

Try this code:

var getDirection = function (ev, obj) {
    var w = obj.offsetWidth,
        h = obj.offsetHeight,
        x = (ev.pageX - obj.offsetLeft - (w / 2) * (w > h ? (h / w) : 1)),
        y = (ev.pageY - obj.offsetTop - (h / 2) * (h > w ? (w / h) : 1)),
        d = Math.round( Math.atan2(y, x) / 1.57079633 + 5 ) % 4;

    return d;
};

$('#yourDiv').mouseover(function (event) {
    var direction = getDirection(event, this);
    if (direction == 0) {
        $(this).html('Top side');
    } else if (direction == 1) {
        $(this).html('Right side');
    } else if (direction == 2) {
        $(this).html('Bottom side');
    } else if (direction == 3) {
        $(this).html('Left side');
    }
});
#yourDiv {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    top: 50px;
    left: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="yourDiv"></div>

getDirection copied from this page by CSS-Tricks which seems to do a similar thing to what you want in a number of different ways.

Upvotes: 3

Related Questions