Get the mouse co-ordinates with jQuery when an element is clicked

Posted in Javascript -

My last jQuery post looked at how to get the mouse co-ordinates with jQuery as the mouse moves around the page or over a particular element. This post looks at how to get the mouse co-ordinates when an element is clicked.

Example

Click the "MOUSE CLICK AREA" below and the x and y co-ordinates in the block below will be updated. Click in different places and it will update. In order for the example below to work, this post must be read in a web browser. If you are viewing this in a feed reader please click through to view the post on my blog.

MOUSE XY
MOUSE CLICK AREA

The jQuery Code

The code to make the above work looks like so, where #mouse-click is the big grey div which is capturing the clicks and #mouse-xy is the div which outputs the result.

$('#mouse-click').click(function(e){
    $('#mouse-xy').html("X: " + e.pageX + " Y: " + e.pageY);
});

Finding the mouse location relative to the element

The above example shows the mouse position on click relative to the document as a whole. In my next jQuery post I show how to get the mouse position within the element i.e. so that clicking the top-left corner of the div will yield 0,0 as the coordinates.



Related posts:


Comments