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.
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:
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.
06/04/2009 - 06:46
thanks!!!
06/22/2009 - 16:57
thank you for your article.
11/16/2009 - 22:18
Sweet, thanks, just what I was looking for.
03/25/2010 - 11:37
thanks
saved my day
04/19/2010 - 18:32
Thanks for this! Exactly what I was looking for!
08/28/2010 - 17:30
Awesome .. saves the day
02/09/2011 - 08:23
Thanks!
Here is the same but inside click handler:
var offset = $(this).offset();
var x = Math.floor(e.pageX - offset.left);
var y = Math.floor(e.pageY - offset.top);
...
}
03/28/2011 - 09:03
I'm afraid .offset() does not account for border/padding. This seems surprisingly complicated to account for, in fact I haven't really found any other way than parsing the calculated css values for border-left-width, etc (which are given as '10px' for example in Firefox). In the end I gave up and decided to just made sure the element I needed relative coords for did not use padding or borders and used wrapper elements if I needed a border. Note that even trying to use the offset and total height/widths to figure out border/padding widths wouldnt be a perfect solution since the widths mgiht not be evenly distributed between top/bottom and left-right (i.e. border-width-left may differ from border-width-right).
Add Comment
[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.