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. User Avatar
    Ben
    Permalink to comment#

    Very cool trick!

  2. User Avatar
    Robin
    Permalink to comment#

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

  3. User Avatar
    Artur Ejsmont
    Permalink to comment#

    I like it too, very simple and works well.

    thanks

  4. User Avatar
    ABDELHAKIM KNIS
    Permalink to comment#

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

  5. User Avatar
    Brandon
    Permalink to comment#

    You’re the bomb! Just what I needed.

  6. User Avatar
    uthaya
    Permalink to comment#

    give some xplanation

  7. User Avatar
    Bob
    Permalink to comment#

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

  8. User Avatar
    kumar
    Permalink to comment#

    Hi,

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

    thanks.

    • User Avatar
      miguel dungan
      Permalink to comment#

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

  9. User Avatar
    Harsh Kanakhara
    Permalink to comment#

    how to get it in percentage ?

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag