Wednesday, September 1, 2010

jQuery Tip: How to get mouse cursor position

In this jQuery tip post, We will see how can we get the mouse cursor position using jQuery.

Earlier I had posted about Provide highlighting effect on mouseover and mouseout, Find which mouse button clicked using jQuery and How to use hover method in jQuery. And in this post, find jQuery way to get the mouse cursor position.

Below jQuery code block will provide X and Y position of mouse cursor.
$(document).ready(function(){
  $(document).mousemove(function(e){
     $('#spnCursor').html("X Axis : " + e.pageX + " Y Axis : " + e.pageY);
  });
});
When the DOM is ready, we listen for mousemove event. Whenever user moves the mouse then this event gets called and we bind the pageX and pageY property to the span element.
See live Demo and Code.
Don't forget to read:
Feel free to contact me for any help related to jQuery. I will gladly help you.