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. :-(

  8. kumar
    Permalink to comment#

    Hi,

    It’s realy nice. how i can get it in percentage.

    thanks.

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

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