Get the mouse co-ordinates with jQuery when an element is clickedGet 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.

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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus