24

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:

<html>
<head>
<title>Assignment 2</title>
<script type="text/javascript">
  var imageURLs = [
       "p1.jpg"
     , "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>
</head>
<body>
<script type="text/javascript">
  document.write(getImageTag());
</script>
</body>
</html>
user5680735
  • 703
  • 2
  • 7
  • 21
  • This could be a duplicate of the following stackover solution: http://stackoverflow.com/questions/2159044/getting-the-x-y-coordinates-of-a-mouse-click-on-an-image-with-jquery – Samuel Toh Jan 19 '16 at 01:29
  • Possible duplicate of [jQuery get mouse position within an element](http://stackoverflow.com/questions/4249648/jquery-get-mouse-position-within-an-element) – Michał Perłakowski Jan 19 '16 at 01:30
  • Guys, I see a jQuery tag here, but no jQuery actually going on... @ChristinaPetrovski Are you even using jQuery? – J. Titus Jan 19 '16 at 01:33

4 Answers4

36

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.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • 1
    So where would I place this, I am a psych major and really do not have any experience with this stuff. Would I place that under my getImageTag function? – Christina Petrovski Jan 19 '16 at 01:35
  • 1
    You would simply copy and paste the code I listed. You can see the example if you click on Run Snippet – Richard Hamilton Jan 19 '16 at 01:40
  • I'm trying and no luck. Do you think its because I don't actually have an Img in my body? They display randomly – Christina Petrovski Jan 19 '16 at 01:46
  • In my situation (wordpress webpage) only `var y = evtent.pageY - $('#element').offset().top;` leads to the full y pixel range. (I had to add an id="element" to the image before.) With `var y = event.pageY - this.offsetTop;` the y-values will start not at 0 but at an offset. This unwanted offset is e.g. due to a css code `body { padding-top: 0.6rem; }` inside the web page. The changed code comes from [link](https://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element). – feli_x Jan 14 '20 at 07:23
  • for jquery solution i preferred this answer to get the pixel coordinates relative to the image https://stackoverflow.com/a/58568016/4097674 – ass-king some questions Jun 07 '21 at 02:45
26

The map solution will only give you the client side pixel coordinates. If you'd like to get the pixel coordinate relative to the original image you need the naturalHeight and naturalWidth information which has height and width of the original image.

code:

 // https://stackoverflow.com/questions/34867066/javascript-mouse-click-coordinates-for-image
  document.getElementById(imageid).addEventListener('click', function (event) {
    // https://stackoverflow.com/a/288731/1497139
    bounds=this.getBoundingClientRect();
    var left=bounds.left;
    var top=bounds.top;
    var x = event.pageX - left;
    var y = event.pageY - top;
    var cw=this.clientWidth
    var ch=this.clientHeight
    var iw=this.naturalWidth
    var ih=this.naturalHeight
    var px=x/cw*iw
    var py=y/ch*ih
    alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
  });

$(document).ready(function() {
    $("img").on("click", function(event) {
        bounds=this.getBoundingClientRect();
        var left=bounds.left;
        var top=bounds.top;
        var x = event.pageX - left;
        var y = event.pageY - top;
        var cw=this.clientWidth
        var ch=this.clientHeight
        var iw=this.naturalWidth
        var ih=this.naturalHeight
        var px=x/cw*iw
        var py=y/ch*ih
        alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="https://upload.wikimedia.org/wikipedia/commons/7/77/Avatar_cat.png" height="256" width="256" alt="kitten">

example

click on IMG at pixel (445.5,334.125) mouse pos (148.5,49) relative to boundingClientRect at (483.5,64) client image size: 640 x 480 natural image size: 1920 x 1080
Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
  • +1 for getBoundingClientRect, because without this method, you won't get the real screen position of the image. this.offsetLeft/Top do give only a relative position (which might be the right value in simple situations, but not in more complex ones), what does not help. – Juergen Oct 27 '19 at 23:01
  • 1
    After scrolling to the bottom of the image returned coordinates are outside the image: "click on IMG at pixel (510,664) mouse pos (255,332) relative to boundingClientRect at (8,-69) client image size: 256 x 256 natural image size: 512 x 512". – Ivan Kovtun Feb 07 '20 at 23:38
  • Thanks much for a plain JS solution! – Carrotman42 Apr 12 '20 at 15:55
  • 1
    Thanks for this nice solution! As @IvanKovtun notes, this gives the wrong coordinates if part of image is scrolled off the screen, since `getBoundingClientRect` is relative to the viewport. To fix this, change `var x = event.pageX - left` to `var x = event.pageX - left - window.scrollX` and similarly for y. (Credit to [this stackoverflow answer](https://stackoverflow.com/questions/16949642/getboundingclientrect-but-relative-to-the-entire-document).) – ELNJ Sep 26 '20 at 18:03
4
$(document).ready(function () {
    $("img").on("click", function (event) {

        $('#img_coordinate').html("X Coordinate: " + (event.pageX - this.offsetLeft) + "<br/> Y Coordinate: " + (event.pageY - this.offsetTop));
    });
});

html

<img src="img/sample.gif" />

<p id="img_coordinate"></p>
Jobelle
  • 2,717
  • 1
  • 15
  • 26
1

little fork ;)

 $(document).ready(function() {
  $('img').click(function(e) {
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();
       w =   $(this).prop("width");        // Width  (Rendered)
   h =  $(this).prop("height");        // Height (Rendered)
      nw =    $(this).prop("naturalWidth") ;  // Width  (Natural)
  nh =  $(this).prop("naturalHeight") ; // Height (Natural)
    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );
        x = Math.round((left*nw)/w);
    y = Math.round((top*nh)/h);
//    $('#img_coordinate').html("Left: " + left + " Top: " + top + "nw: "+nw+" nh: "+nh +"x: "+x+" y: "+y);
    $('#img_coordinate').html("click x: "+x+" y: "+y);

  });
});
J. Doe
  • 119
  • 1
  • 8