Tutorial Get X, Y Coordinates of Mouse Within Box

by in , 0

The below code will give you the X, Y coordinates of a mouse click within a given box. Removing all the stuff about the offset, you can easily get the X, Y coordinates of the click relative to the browser window.

$(function() {
$("#demo-box").click(function(e) {

  var offset = $(this).offset();
  var relativeX = (e.pageX - offset.left);
  var relativeY = (e.pageY - offset.top);

  alert("X: " + relativeX + "  Y: " + relativeY);

});
});

Example

Click in the box below

Leave a Reply