Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Get Cursor Coordinates Using jQuery

It's fairly easy to get the Coordinates of your cursor using jQuery. While this information might not be particularly useful to a lot of developers, there are definitely occasions where the x and y coordinates of your cursor can be particularly useful.

The code snippet below shows you how to find the x and y coordinates of a cursor when it's within a particular HTML element (a box, a div...whatever you like), and then display those coordinates through an alert message. The code can be totally customized to have the coordinates instead print to the console, or to have the cursor coordinates be found within the body or the window rather than within a particular element. Use the snippet below as a jumping off point for your cursor-finding code:

$(function() {
$("#coordinates-box").click(function(e) {
  var offset = $(this).offset();
  var relativeX = (e.pageX - offset.left);
  var relativeY = (e.pageY - offset.top);
  alert("X coordinate: " + relativeX + "  Y coordinate: " + relativeY);
10
});
11
});




This post first appeared on JQuery By Example, please read the originial post: here

Share the post

How to Get Cursor Coordinates Using jQuery

×

Subscribe to Jquery By Example

Get updates delivered right to your inbox!

Thank you for your subscription

×