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.
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.
Share Improve this question edited Jul 25, 2019 at 16:04 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 28, 2011 at 4:48 user1946705user1946705 2,88814 gold badges43 silver badges58 bronze badges 1- 1 Are you looking for imagemap? – Mrchief Commented Jul 28, 2011 at 4:58
3 Answers
Reset to default 6On 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.
You can get the mouse position easily, and then you can add something to that point relative to the image.
Here's an example of mouse position: jquery.