Get 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.
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:
- jQuery: Mouse co-ordinates within the element when mouseover or click an element (Wednesday, October 28th 2009)
- Get the mouse co-ordinates with jQuery when an element is clicked (Friday, October 9th 2009)
- How to tell if an element is visible with jQuery (Friday, September 18th 2009)
- Running a function with jQuery when the window is resized (Tuesday, August 25th 2009)
- Use jQuery's data() method to store data in the DOM (Tuesday, July 7th 2009)
- Use append() to add text/html to an element with jQuery (Friday, June 5th 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.
