Search code examples
jqueryonmouseovermouse-position

How to calculate the mouse position from the center of an element in Jquery


I'm trying to find a way of calculating the mouse position from the center of an element.

I've got as far as e.pageX and e.pageY on the mouse over event, but I can't get my head around calculating its position relative to the elements center.

I can't think of the equation


Solution

  • You need to first get the object's center point, X & Y (objCenterX & objCenterY in the code, below), then subtract that from the mouse's current coordinates.

    This should do it for you:

        $("#test").mousemove(function (event) {
            var objLeft = $("#test").offset().left;
            var objTop = $("#test").offset().top;
    
            var objCenterX = objLeft + $("#test").width() / 2;
            var objCenterY = objTop + $("#test").height() / 2;
    
            $("#results").text("Left:" + (event.pageX - objCenterX) + ", Top:" + (event.pageY - objCenterY));
        })