How to Get Coordinates of Click in Javascript

How to Get Coordinates of Click in Javascript

I built the Where’s Waldo game using React a while ago and it was hard. It wasn’t the implementation that was hard, it was how to get the location/coordinates of a click in the puzzle image irrespective of the screen resolution or zoom. Basically, I had to make sure the coordinates of the characters would remain the same on different screen sizes and zoom.

For those who are not familiar with this game, Where's Waldo is a photo-tagging app where users are presented with a large photograph that contains several elements the user is meant to find, e.g. Waldo, The Wizard, Wilma etc. The user will make selections for each character and they will get feedback on whether they are correct or not. You can play the game or view it on GitHub. waldo.gif

Let’s code!

//Attach event listener to image
picture.addEventListener(‘click’, functionThatHandlesThisClickEvent)

const functionThatHandlesThisClickEvent = e => {

const target = e.target;
const xCoord = Math.floor((e.pageX - target.offsetLeft) / target.width * 10000)/100;
Const yCoord = Math.floor((e.pageY - target.offsetTop) / target.width * 10000)/100;
return { xCoord, yCoord }
}

Clicking on the image will return the x,y coordinates of the image in percentage of the image.