Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mouse position inside parent div with javascript/jQuery [duplicate]

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?

like image 609
user1609221 Avatar asked Aug 18 '12 19:08

user1609221


1 Answers

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

like image 156
JJJ Avatar answered Sep 20 '22 08:09

JJJ