views:

44

answers:

3

I have an input set to a type of image:

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

I want to attach a function so that I can get the X & Y coordinates where a person clicked:

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

I cannot find the X & Y coordinates inside 'data'. What am I doing wrong?

A: 

The parameter to the handler function (the "Event" object) has "pageX" and "pageY" values. Do the math with those and the "position()" or "offset()" for your img element (whichever works better; I find it really confusing to predict which of the two will work in any given situation).

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

I'm not sure I understand why you're binding to the "submit" event - is the image inside a "submit" button or something?

Pointy
The way I understand it, an image input takes the place of a submit input. So clicking on the image has the same action as clicking on a submit button.
Robert
uhhh ... can you post your HTML? That sounds pretty fishy to me. Where did you come across that suggestion?
Pointy
Oh duhhhh -- you DID post your HTML :-) Sorry. Anyway, the way that's set up will not cause a form submit to happen. You can attach a "click" handler to the image, however, and use that to call "submit" on the form.
Pointy
er, `input type="image"` does cause a submit to occur. You can replace it with a dud image and script it yourself as in Nick's answer, but then the submit button won't work without JavaScript enabled, and other form validation won't occur if you press Enter to submit the form instead of clicking. You can have a hybrid though, where the co-ordinates are caught by input-onclick, and remembered by validation code in form-onsubmit.
bobince
Oh OK, you're right I guess; it's been a really long time since I did anything like that :-) Sorry to mislead you, @jerone. Also thanks for correcting me so informatively @bobince.
Pointy
+2  A: 

There's a good tutorial on this here, in the 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
  //e.g. $("#usa_map_x").val(x); $("#usa_map_y").val(y);

  //Submit the form
  $('#MapForm').submit();
});
Nick Craver
A: 

You can't get the x and y values, because the submit executed before the form submition.

From the jQuery API:

... The submit event is sent to an element when the user is attempting to submit a form...

... This happens prior to the actual submission ...

jerone