Home / jQuery: Mouse co-ordinates within the element when mouseover or click an element

jQuery: Mouse co-ordinates within the element when mouseover or click an element

Following up a couple of earlier posts about get the mouse co-ordinates with jQuery and how to get the co-ordinates when an element is clicked, this post looks at how to do both of these but with co-ordinates relative to the element itself so i.e. the top left coordinate is 0, 0 instead of some other value relative to the page.

jQuery Documentation

How to get the co-ordinates is documented here in the jQuery documentation/tutorials but doesn’t show a working example of getting the position relative to the element (just the page as a whole), whereas I have a working example here. It also doesn’t show how to get the mouse position as you move your mouse over an element relative to the element.

Mouse position within element on click

Here’s an example of this working. If you are reading this article in a feed reader then please click through to read it in a web browser as it will not work. Click anywhere on the large block and it will show the mouse X,Y coordinates relative to the element itself.

MOUSE XY
MOUSE CLICK AREA

And here’s the code which makes the above work. The classes are used to style the boxes and the ids for referencing them in the click handler etc. The offsetLeft and offsetTop are subtracted from the current mouse position relative to the page to work out the mouse position relative to the element.

<div id="example1-xy" class="mouse-xy">MOUSE XY</div>
<div id="example1" class="mouse-click">MOUSE CLICK AREA</div>
<script language="Javascript">
    $('#example1').click(function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        $('#example1-xy').html("X: " + x + " Y: " + y); 
    });
</script>

Mouse position within element on mouseover

And here’s an example of the same but it will update the MOUSE XY box whenever the mouse is moved over the mouse over area.

MOUSE XY
MOUSE OVER AREA

And the code. The offsetLeft and offsetTop are subtracted from the current mouse position relative to the page to work out the mouse position relative to the element.

<div id="example2-xy" class="mouse-xy">MOUSE XY</div>
<div id="example2" class="mouse-click">MOUSE CLICK AREA</div>
<script language="Javascript">
    $('#example2').mousemove(function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        $('#example2-xy').html("X: " + x + " Y: " + y); 
    });
</script>