Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the X/Y coordinates of a mouse click on an image with jQuery [duplicate]

Tags:

jquery

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

like image 602
Ron Harlev Avatar asked Jan 29 '10 00:01

Ron Harlev


1 Answers

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.

like image 114
Brian McKenna Avatar answered Sep 20 '22 01:09

Brian McKenna