Get the mouse co-ordinates with jQueryGet the mouse co-ordinates with jQuery

Posted October 6th, 2009 in Javascript

jQuery's mousemove function can be used to track the mouse x and y co-ordinates either for an entire document or just when mousing over a particular element.

Example

The example used below shows the mouse co-ordinates as you move the mouse over the grey block labelled "MOUSE CAPTURE AREA". When you mouse outside the block, the co-ordinates are no longer updated.

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 CAPTURE AREA

The jQuery Code

The code to make the above work looks like so:

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

#mouse-capture is the grey div above, and #mouse-xy is the div which has the co-ordinates.

To update the mouse co-ordinates where-ever it is in the page, do this instead:

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

Finding out the mouse location on click

My next jQuery post shows how to get the mouse co-ordinates when an element is clicked and this is then followed up showing how to get the position within the element rather than relative to the page as a whole.

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