IMG onclick

img onclick

TL;DR Summary – IMG onclick

There are some awesome things you can do with img onclick functionality. In this tutorial I’m going to show you a few of them you can use on your image element.

First thing you can easily do is create an entire image gallery using only one img element and you can switch between the images just by changing the src attribute.

So when you click on the image then different image appears.

Here is the minimum code you need to achieve this:

<img id="gallery" width="600" src="forest.jpg" />

  const image = document.getElementById('gallery');
  image.onclick = () => {
    image.setAttribute('src', 'sandbeach.jpg');

So initially you had an image of the forest like this:

img onclick forest

Once you click on the image then its src path will change and browser will load another picture of the sand beach:

img onclick beach

And that’s it.

You can use this code as a starting point to create additional features but is all you need to create a gallery using img onclick functionality.

And if you want to really speed up your programming career:

raise salary by 30%

More Details

Another cool thing you can do is invert the image color when you click on it.

Below is the full code that shows you how you can achieve the exact effect you can see on the image on the top:

  body { 
    background-color: orange; 
    padding: 300px;
    text-align: center;

<img id="gallery" width="600" src="sandbeach.jpg" />

  let toggle = true;
  const image = document.getElementById('gallery');
  image.onclick = () => { = `invert(${toggle ? 100 : 0}%)`;
    toggle = !toggle;

And those are some of the cool things you can do with img onclick functionality. 

Until next time,
Senior Software Developer