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:
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.
Source Files:
thanks!!!
thank you for your article.
Sweet, thanks, just what I was looking for.
thanks saved my day
Thanks for this! Exactly what I was looking for!
Awesome .. saves the day
Thanks! Here is the same but inside click handler:
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).