Grow your CSS skills. Land your dream job.

Last updated on:

Get X, Y Coordinates of Mouse Within Box

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

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.

  6. uthaya
    Permalink to comment#

    give some xplanation

  7. Permalink to comment#

    Works great in IE, but not in Safari. :-(

Leave a Comment

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".