Sometimes, we want to add img element onclick event handler with JavaScript.
In this article, we’ll look at how to add img element onclick event handler with JavaScript.
How to add img element onclick event handler with JavaScript?
To add img element onclick event handler with JavaScript, we set the onclick attribute to the JavaScript code we want to run.
For instance, we write
<img src="https://picsum.photos/30/30" onclick="window.open(this.src)" />
to set the onclick attribute to window.open(this.src) to call window.open with the img element’s src attribute to open the image in a new window when we click the image.
Conclusion
To add img element onclick event handler with JavaScript, we set the onclick attribute to the JavaScript code we want to run.