treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Get X, Y Coordinates of Mouse Within Box

Last updated on:

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

View Comments

Comments

  1. Permalink to comment#

    Very cool trick!

  2. Permalink to comment#

    I like thisone. It’s very usefull in future projects.

  3. I like it too, very simple and works well.

    thanks

  4. ABDELHAKIM KNIS
    Permalink to comment#

    VERY COOL TIP THANKS CHRIS YOU ARE M3ALLEM (MEANS master in arabic)

  5. Permalink to comment#

    You’re the bomb! Just what I needed.

Leave a Comment

Use markdown or basic HTML and be nice.