jQuery code to get the x, y coordinate of mouse click of any visible element.
While trying to get the x and y coordinates of the location where a user clicked on a particular image, i just stumbled upon a "not-a-definite-solution" with posts written on different blogs and a lot of different techniques people have used.
So here is my version with bits and pieces put together.
First lets get the x,y coordinates of any given element on the page.
File: jquery.elementlocation.js
jQuery.fn.elementlocation = function() { var curleft = 0; var curtop = 0; var obj = this; do { curleft += obj.attr('offsetLeft'); curtop += obj.attr('offsetTop'); obj = obj.offsetParent(); } while ( obj.attr('tagName') != 'BODY' ); return ( {x:curleft, y:curtop} ); };
Add above javascript file into any html page and we can do a
location = $("element-selector").elementlocation(); // access with location.x and location.y
Next, we use the pageX and pageY property of the eventObject to get the location in the webpage where any event occured. Then finally substract the x and y coordinate of image itself to get the relative position of the event.
<html> <head> <script src="jquery-1.3.2.min.js"></script> <script src="jquery.elementlocation.js"></script> <script> $(document).ready( function() { $("#clickable-image").mousemove( function( eventObj ) { var location = $("#clickable-image").elementlocation(); var x = eventObj.pageX - location.x; var y = eventObj.pageY - location.y; $("#x-coordinate").text( x ); $("#y-coordinate").text( y ); }); }); </script> </head> <body> <div>Click on the image to get the coordinate.</div> <div><img id="clickable-image" src="test-image.png"/></div> <p>X:<span id="x-coordinate"></span></p> <p>Y:<span id="y-coordinate"></span></p> </body> </html>
All the files are attached with the post.
Comments are welcome.
| Attachment | Size |
|---|---|
| click-demo.html | 696 bytes |
| jquery.elementlocation.js.txt | 358 bytes |
| jquery-1.3.2.min_.js.txt | 55.91 KB |
| test-image.png | 180.56 KB |


Comments
hi
thank for the post
great site.
gr8 site . keep it up .I found the above post very useful to me . thank you for posting.
I am able to get this script to work but it gives me different x,y coordinates in IE than in FF and Chrome.
Thanks a lot. This helped me a lot.
Great post!
رائعة
لكنها لا تعمل
Great but doesn't working
The following works without the need for any additional plugin. It uses jQuery.offset() which was added in version 1.2.
Just to confirm this works, I tested it using jQuery versions
r u using this option.its totally waste..lol.
actually i need a code in Java.the concept is the rectangular box has to place next to the previous box by getting order while clicking he mouse.
on the second click the box have to place next to the first and third click next to tat as so on...
Post new comment