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:
- Get an element's position relative to the document with jQuery (Tuesday, February 9th 2010)
- 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)

Comments
blog comments powered by Disqus