How to get the mouse click coordinates for image with JavaScript?

Sometimes, we want to get the mouse click coordinates for image with JavaScript.

In this article, we’ll look at how to get the mouse click coordinates for image with JavaScript.

How to get the mouse click coordinates for image with JavaScript?

To get the mouse click coordinates for image with JavaScript, we can add a click event listener to the img element.

For instance, we write:

<img src="https://picsum.photos/200/300">

to add an img element.

Then we write:

const img = document.querySelector("img")
img.onclick = (e) => {
  const x = e.pageX - e.target.offsetLeft;
  const y = e.pageY - e.target.offsetTop;
  console.log(x, y);
}

to select the img element with querySelector.

Then we set img.onclick to a function that gets the x and y coordinates of the mouse click in the page with e.pageX - e.target.offsetLeft and e.pageY - e.target.offsetTop.

Conclusion

To get the mouse click coordinates for image with JavaScript, we can add a click event listener to the img element.