Home / Get the mouse co-ordinates with jQuery

Get the mouse co-ordinates with jQuery

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.