While writing the next jQuery tutorial I needed to identify and locate where the mouse was on the page. Tracking mouse position on the page with jQuery is easy. You don’t need to check what browser the script is running like it is used to be with plain JavaScript. To identify where the mouse is in jQuery all you have to do is to read event object’s .pageX
and .pageY
properties.
Example:
$().mousemove(function(e){ // e.pageX - gives you X position // e.pageY - gives you Y position });
The above jQuery code is binding a new ‘on mouse move’ event to the current document and triggered every time mouse moves. The coordinates are calculated in pixels from top left corner of the document. See the above code in action.
You may also want to know the coordinates of the mouse relative to some <div> or an element. Since jQuery returns mouse position relative to the document root, by subtracting element’s position from document root you get mouse positions relative to that element. Long story short here is the code to do just that:
$("#someDiv").click(function(e){ var relativeX = e.pageX - this.offsetLeft; var relativeY = e.pageY - this.offsetTop; });
Don’t forget that you can bind any mouse event to any element and then get mouse positions. You can easily create a draggable object with click
and mousemove
events by simply setting the CSS top and left values to .pageX and .pageY.
Anyway, that’s how you locate and handle mouse positions in jQuery. As always, you don’t need to worry about cross browser compatibility issues while using jQuery. To learn more see more examples here.