Javascript mouse click coordinates for image

Christina Petrovski picture Christina Petrovski · Jan 19, 2016 · Viewed 34.9k times · Source

The assignment says "Your task is to write an HTML file that contains JavaScript that will randomly display one of the images above. If the page is refreshed in the browser, you should get another random image." so I did it.

Now it says "When the user clicks anywhere on the image, display an alert window that shows the X and Y position of where the click occurred relative to the image". Here is my code:

Answer

Richard Hamilton picture Richard Hamilton · Jan 19, 2016

You can actually use HTML for this. The image tag has an attribute known as ismap.

What this attribute does is specify that an image is part of a server-side image map. When clicking on such map, the click coordinates are sent to the server as a url query string.

Images must be nested under links for this to work. Here is an example

<a href="http://www.google.com">
    <img src="myimage.png" alt="My Image" ismap">
</a>

If you can't use image maps for this, here is a javascript/jquery solution

First, you need to include the jQuery library at the bottom of your body tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  

$(document).ready(function() {
    $("img").on("click", function(event) {
        var x = event.pageX - this.offsetLeft;
        var y = event.pageY - this.offsetTop;
        alert("X Coordinate: " + x + " Y Coordinate: " + y);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://vignette1.wikia.nocookie.net/seraphina/images/b/b2/Dragonseraphina.jpg/revision/latest?cb=20160103194957" height="200" width="200" alt="dragon">

You listen for the click event, and pass in event as the parameter.

The event.pageX property returns the position of the mouse pointer, relative to the left edge of the document.