I would like to use jQuery to get the X/Y coordinates of a click event on an image. The coordinates should be relative to the image, not relative to the whole page
+2
A:
You can use clientX
and clientY
to get the position of the mouse in the window. You can also use jQuery's offset
to get the position of an element.
So, it should be clientX - offset.left
for how far from the left of the image and clientY - offset.top
for how far from the top of the image.
Here is an example:
$(document).ready(function() {
$('img').click(function(e) {
var offset = $(this).offset();
alert(e.clientX - offset.left);
alert(e.clientY - offset.top);
});
});
I've made a live example here and here is the source.
To calculate how far from the bottom or right, you would have to use jQuery's width
and height
methods.
Brian McKenna
2010-01-29 00:36:38
@Brian : Thanks so much for your solution!!! This resolves my problem when webpage zooms in/out.
Michael Mao
2010-03-12 07:01:50