How to use jQuery to get mouse cursor coordinates when mouse moves

I was exploring on how to create drag and drop elements on a webpage. The first thing that I have to know is to detect my mouse cursor coordinates when my mouse moves.

This post documents my exploration in using jQuery to detect mouse cursor coordinates when I move my mouse.

Registering a JavaScript callback function to listen to mouse movements

Getting notified when the mouse moves is easy with jQuery:

$(document).mousemove(function(event) {
    $('#mousePosition').html('Your mouse is currently at: ' 
                                + event.pageX +', '+ event.pageY);
});

I first wrap the document object with the jQuery function. I then call the mousemove function, passing in a callback function that accepts an event object. By doing so I instructed jQuery that I want it to help me listen for mouse movements that happens on the entire webpage.

In the callback function, I use jQuery to look for a element marked with mousePosition as its id and set the coordinates of the mouse as its html contents. The pageX and pageY attributes of the event object give me the coordinates of my mouse cursor.

The entire HTML document

After constructing the JavaScript codes, I proceed to construct the HTML document by referencing my little HTML code reference. I then include the JavaScript codes at the head section of the document. The following is the entire HTML document that I use for realizing this proof of concept.

<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){	   
            $(document).mousemove(function(event){
	        $('#mousePosition').html('Your mouse is currently at: ' 
                                            + event.pageX +', '+ event.pageY);
            }); 
	});
    <script>
</head>
<body>
<div id="mousePosition">
No mouse movement detected yet.
</div>
</body>
</html>

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.