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
You can use pageX
and pageY
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 pageX - offset.left
for how far from the left of the image and pageY - 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.pageX - offset.left); alert(e.pageY - 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With