Possible Duplicate:
jQuery get mouse position within an element
I have a page and inside that page I have a div. If the user clicks inside that div it'll store the X/Y co-ordinates of where they clicked inside that div.
E.g. if I clicked in the top left corner of the div (no matter where the div was placed on the page) it'd return approximately 0, 0.
Is this even possible? and if so, could you tell me how - or even point me in the right direction?
Use pageX
property of the event to get the x coordinate relative to the page and pageY
to get the y coordinate, then substract the element's coordinates to get the position relative to the element.
$( '#target' ).on( 'click', function( e ) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
});
Demo: http://jsfiddle.net/WhrFt/
Official tutorial on jquery.com: http://docs.jquery.com/Tutorials:Mouse_Position
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With