Treehouse: 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. Ben
    Permalink to comment#

    Very cool trick!

  2. Robin
    Permalink to comment#

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

  3. Artur Ejsmont
    Permalink to comment#

    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. Brandon
    Permalink to comment#

    You’re the bomb! Just what I needed.

  6. uthaya
    Permalink to comment#

    give some xplanation

  7. Bob
    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.

    • miguel dungan
      Permalink to comment#

      uhmm try x pos/width of box
      and y pos/height of box

  9. Harsh Kanakhara
    Permalink to comment#

    how to get it in percentage ?

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```