Choose location in image using jQuery

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

The base event.pageX / event.pageY does not take into account the scroll and position of the element. The combination of Document.getScrollTop () and element.getAbsoluteTop (the location of the mouse in the image ) does not look good (it may not even work in all browsers, as far as I know).

Is there an easier way?

+3
source share
1 answer

This seems simple enough:

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

See demo →

+6
source

All Articles