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.

2
  • Do you want to get the coordinates relative to the document or to the image that was clicked? Commented Aug 6, 2011 at 21:48
  • 1
    sorry. Relative to the image. Commented Aug 6, 2011 at 21:49

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@Andre: I'm rather interested too. I'll do some digging.
@Andre: The interwebs don't yield much information about this input type. Even .serialize() doesn't give you the coordinates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.