We can find the X and Y coordinates using jQuery pageX and pageY events to locate the mouse position on the image or any element to be precise. We can get the location of the mouse either by hovering it over the image or by clicking the image.
We will add a Sprite image in our web page, which has three small images embedded together in a single image file. We will also add a DIV element, which will show us the coordinates when we move, hover or click on the image.
<html> <head> <title>X, Y Coordinates using jQuery</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> </head> <body> <div style="width:300px;"> <div><img src="sprite.png" alt="" /></div> <div style="padding-top:20px;"> <div id="coord"></div> </div> </div> </body> </html>
To get the precise X, Y coordinates of the image we will use jQuery offset() method to remove spaces between the window and image container. The DIV is acting as a container to the image. This way even if we add a little padding to the container, the coordinates of the image is precise.
<script> $(document).ready(function() { $('img').click(function(e) { var offset = $(this).offset(); var X = (e.pageX - offset.left); var Y = (e.pageY - offset.top); $('#coord').text('X: ' + X + ', Y: ' + Y); }); }); </script>
Click the below icons
<script> $(document).ready(function() { $('img').on("mousemove", function(e) { var offset = $(this).offset(); var X = (e.pageX - offset.left); var Y = (e.pageY - offset.top); $('#coord').text('X: ' + X + ', Y: ' + Y); }); }); </script>
Demo - Hover the Mouse over the images
We have seen how x, y coordinates can be located in an image inside another image, in fact these properties are not confined to images only, you can try with other HTML elements like DIV or P.
Sprite images are a collection of multiple image bundled together in a single image. We will discuss about Image Sprites, its advantages and use with CSS, in another article very soon.