3

is there an easy way to find where user clicked inside an image (div, ...), relative to top-left corner of the element? (using js/jquery)

Basic event.pageX/event.pageY does not take into account scrolling and element position. Combining Document.getScrollTop() and element.getAbsoluteTop ( Mouse click location on an image ) does not look nice at all (may not even work on all browsers as far as I know).

Is there a simpler way to this?

Community
  • 1
  • 1
Ondrej Skalicka
  • 3,046
  • 9
  • 32
  • 53
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1128643/get-accurate-position-for-a-click-on-a-linked-image-using-jquery – Adam Terlson May 13 '11 at 22:10

1 Answers1

6

This seems simple enough:

$('#yourImg').click(function(e){
    var x = e.pageX - e.target.offsetLeft,
        y = e.pageY - e.target.offsetTop;
});

See demo →

mVChr
  • 49,587
  • 11
  • 107
  • 104