Is it possible to find where the user clicked on the image?
I have an image - and onto the image the user can click. And I am trying to find a way, how to get the place, when the user clicked.
On image click you can find the coordinates where the user clicked using the event object.
$("imageSelector").click(function(e){
var pos = $(this).position();
//The following are the x/y coordinates of the mouse click relative to image.
var x = e.pageX - pos.left;
var y = e.pageY - pos.top;
});
Don't be fooled by methods that fail to take margin, padding, and border into account!
This is the code you need. :
$("#myImage").click ( function (evt) {
var jThis = $(this);
var offsetFromParent = jThis.position ();
var topThickness = (jThis.outerHeight(true) - jThis.height() ) / 2;
var leftThickness = (jThis.outerWidth (true) - jThis.width () ) / 2;
//--- (x,y) coordinates of the mouse click relative to the image.
var x = evt.pageX - offsetFromParent.left - leftThickness;
var y = evt.pageY - offsetFromParent.top - topThickness;
} );
See it in action at jsFiddle.
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