Javascript: Get X, Y Coordinates of Click in Image

13,552

You should use offsetX and offsetY from you event object to get the mouse coordinates relative to the element that fires the event. clientX and clientY will return mouse coordinates relative to the window, as you have noted.

Event object properties

This should do the trick

function clickHotspotImage(event) {
    var xCoordinate = event.offsetX;
    var yCoordinate = event.offsetY;
    var hotspotlist = document.getElementById('hotspot_list').value;
    document.getElementById('hotspot_list').value = document.getElementById('hotspot_list').value + '\n' + xCoordinate + ',' + yCoordinate;
}
Share:
13,552
Steve G.
Author by

Steve G.

Updated on August 21, 2022

Comments

  • Steve G.
    Steve G. almost 2 years

    here's my latest problem.

    I'm trying to get the X and Y coordinates of where a user clicks inside an image. Regardless of where it's positioned in the user's window, the zoom, the scroll position, the size of window, what the user had for breakfast, etc., the X,Y coordinates have to take into account only what position the user clicks in the image but not include the position of the image in the screen, i.e. the upper left point in the image is 0,0. (Hope I'm explaining this clearly.)

    The reason I say this is because, in my current JavaScript function, I'm getting the X,Y coordinates of something, but I'm not sure exactly what. I think it's the position of where the user clicks in the overall window, but not in the image. This means that the X,Y coordinates change if the position of the image is different, if the user has scrolled, if I move the image somewhere else in the page, etc. Here's my current HTML code:

    <img id="hotspot_image" name="hotspot_image" style="width: 50%" src="misc/pages/hotspotimage.jpg" alt="Hotspot image" onclick="clickHotspotImage(event);"/>
    

    And here's my Javascript function:

    function clickHotspotImage(event) {
        var xOffset = document.getElementById('hotspot_image').offsetLeft;
        var xCoordinate = event.clientX;
        var yOffset = document.getElementById('hotspot_image').offsetTop;
        var yCoordinate = event.clientY;
        var hotspotlist = document.getElementById('hotspot_list').value;
        document.getElementById('hotspot_list').value = document.getElementById('hotspot_list').value + '\n' + xCoordinate + ',' + yCoordinate;
    }
    

    The last few lines of code in there take that X,Y coordinate pair and add it to the end of a list contained in a <textarea> tag called hotspot_list. Does anyone know if I'm on the right track or can point me in the right direction, or knows what missing piece I need to get that true X,Y coordinate? Thanks!