How to add a click event handler to an image with JavaScript?

Sometimes, we want to add a click event handler to an image with JavaScript.

In this article, we’ll look at how to add a click event handler to an image with JavaScript.

How to add a click event handler to an image with JavaScript?

To add a click event handler to an image with JavaScript, we can select the image and set its onclick property to a click event handler function.

For instance, we write:

<img src="https://i.picsum.photos/id/572/200/300.jpg?hmac=Rt4zD8IxoA-nMVDrBQ72mgbTVRfQ6OwW3MhWy_3lpdk" />

to add an image.

Then we write:

const img = document.querySelector('img')
img.onclick = () => {
  console.log('clicked')
}

Then we select the img element with document.querySelector.

Next, we set its onclick property to a function that runs when we click on the image.

As a result, we see 'clicked' logged when we click on the image.

Conclusion

To add a click event handler to an image with JavaScript, we can select the image and set its onclick property to a click event handler function.