Javascript Mouse Click Coordinates For Image

- 1 answer

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:

<title>Assignment 2</title>
<script type="text/javascript">
  var imageURLs = [
     , "p2.jpg"
     , "p3.jpg"
     , "p4.jpg"
  function getImageTag() {
    var img = '<img src=\"';
    var randomIndex = Math.floor(Math.random() * imageURLs.length);
    img += imageURLs[randomIndex];
    img += '\" alt=\"Some alt text\"/>';
    return img;
<script type="text/javascript">



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 target="_blank" rel="nofollow noreferrer" href="">
    <img src="myimage.png" alt="My Image" ismap">

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=""></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=""></script>

<img src="" 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.