jQuery Snippet - Relative Mouse Position

Skill

jQuery Snippet - Relative Mouse Position

Posted in:

For whatever reason, there may be times when the mouse position relative to the page document is just not specific enough. Sometimes you may want the position as it relates to a specific element. Maybe you want the position of something in an image, maybe you are just curious, it doesn't matter. What does matter is that you want those coordinates. Thankfully, with jQuery, we can easily do this.

X,y

In this demo, you can clearly see two sets of coordinates. One relates to the entire HTML document, and the other pair relates specifically to the div, with the top left corner being the zero point. To do this, all we need is to subtract the element's "offset" from the current mouse coordinates:

function rPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY - offset.top;

  return {'x': x, 'y': y};
}

What this function does is take in an element's ID and the mouse position, then it subtracts the elements css offset from the mouse coords. This magical "offset" is not to be confused with the css property offset, rather it is a calculated total offset in relation to the HTML document. Such things as padding and margins can effect this offset, and thankfully jQuery does all this calculating for us.

You never know when the relative mouse position might come in handy, and now you know how to get it using jQuery. This wraps it up for this short one, just remember that when you need coding help, all you have to do is Switch On The Code.

keithics
06/04/2009 - 06:46

thanks!!!

reply

johnaspnet
06/22/2009 - 16:57

thank you for your article.

reply

Anonymous
11/16/2009 - 22:18

Sweet, thanks, just what I was looking for.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors