Get the mouse co-ordinates with jQuery when an element is clicked
Posted October 9th, 2009 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.
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:
- jQuery: Mouse co-ordinates within the element when mouseover or click an element (Wednesday, October 28th 2009)
- Get the mouse co-ordinates with jQuery (Tuesday, October 6th 2009)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
