6

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?

Community
  • 1
  • 1
user1609221
  • 63
  • 1
  • 1
  • 3
  • 1
    Looks like it's been answered here: http://stackoverflow.com/questions/4249648/jquery-get-mouse-position-within-an-element – Strille Aug 18 '12 at 19:56

1 Answers1

14

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

JJJ
  • 32,902
  • 20
  • 89
  • 102