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
});

SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..