jQuery Tracking The Position Of The User's Mouse

You would want to use the "pageX" and "pageY" methods. For example, let's say that we had a single paragraph tag in our document. If we wanted the paragraph tag's text to dynamically display the coordinates of the user's mouse, we could do the following:

$(document).ready(function()
{
$().mousemove(function(e)
{
$('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
});

View The Example

This code says the following - When the document is ready to be manipulated, we'll listen for when the user moves his or her mouse (mousemove). When it does, we'll set the html of our paragraph tag to display the coordinates (e.pageX and e.pageY, respectively).

5
Your rating: None Average: 5 (1 vote)

Jeffrey Way is a freelance web developer based in Nashville, TN. When not losing his sanity staring at his computer, he enjoys spending time with his family and beautiful fiance. Jeffrey is a DZone MVB and is not an employee of DZone and has posted 3 posts at DZone. You can read more from them at their website.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

AmmyWang replied on Thu, 2009/07/02 - 8:15am

Thanks for the article. Very short and to the point.

I found this article about mouse positing in jQuery and found it very useful. It gives you a little insight and shows some more example.

Great article, thanks.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.