How to get x & y corrdinate from image input?

I have an input set for an image type:

<form id="MapForm" action="#"> <input type="image" src="usa.jpg" id="usa_map" alt="USA"/> </form> 

I want to add a function so that I can get the X and Y coordinates that the person clicked on:

 $('#MapForm').submit(ClickOnMap); function ClickOnMap(data) { return false; } 

I cannot find the X and Y coordinates inside the "data". What am I doing wrong?

+4
source share
3 answers

There is a good tutorial here in jQuery docs :

 $('#usa_map').click(function(e){ //Grab click position, mis the offset of the image to get the position inside var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; alert('X: ' + x + ', Y: ' + y); //set 2 form field inputs if you want to store/post these values //eg $("#usa_map_x").val(x); $("#usa_map_y").val(y); //Submit the form $('#MapForm').submit(); }); 
+3
source

The parameter of the handler function (the "Event" object) has the values ​​"pageX" and "pageY". Do the math with those, and "position ()" or "offset ()" for your img element (depending on what works best, it seems to me confusing to predict which of the two will work in any situation).

In other words, the "position ()" of the img element gives the "top" and "left" value. Subtract those from "pageY" and "pageX", and you have a position inside the image itself relative to its upper left corner.

I'm not sure I understand why you are attached to the send event - is this the image inside the send button or something else?

0
source

You cannot get the x and y values ​​since submit is executed before the form is submitted.

From the jQuery API :

... A submit event is dispatched to an element when a user tries to submit a form ...

... this happens before the actual presentation ...

0
source

Source: https://habr.com/ru/post/1301217/


All Articles