3

Example:

<form>
<input type="image" id = 'toothsImage' src="someImg.jpg" alt="Submit" />
</form>

Image form TYPE acts much like the INPUT TYPE=SUBMIT field, but unlike the SUBMIT field, the coordinates of the image that were activated are sent back to the server in addition to the rest of the form data. So - when one clicks on input=image - request will be appended with click coordinates like so:

x=1&y=2

My question is - how can one retrieve these coordinates using javascript without submitting the form.

P.S 1: I'm aware that click coordinates can be calculated in many ways. I know them and can easily use them. I'm interested in this approach only since here browser calculates everything automatically.

P.S 2: I need to get coordinates that are relative to the image, not the document.

Stann
  • 13,518
  • 19
  • 65
  • 73

1 Answers1

5

Looks like offsetX, offsetY aren't available or are unreliable in some browsers. I would recommend using pageX and pageY since those are normalized by jQuery. Combine that with the offset of the element being clicked and you should be in business:

$("input[type='image']").click(function(event) {
    var elOffsetX = $(this).offset().left,
        elOffsetY = $(this).offset().top,
        clickOffsetX = event.pageX - elOffsetX,
        clickOffsetY = event.pageY - elOffsetY;

    // clickOffsetX and clickOffsetY are the clicked coordinates,
    // relative to the image.
});

Example: http://jsfiddle.net/andrewwhitaker/87NYk/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • This sure does work, no questions. but I'm rather interested in how to get the values that are automatically calculated by the browser when one clicks on input type="image" without making a trip to the server. – Stann Aug 06 '11 at 22:06
  • @Andre: I'm rather interested too. I'll do some digging. – Andrew Whitaker Aug 06 '11 at 22:12
  • @Andre: The interwebs don't yield much information about this input type. Even `.serialize()` doesn't give you the coordinates. – Andrew Whitaker Aug 06 '11 at 22:37