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" />

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

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.

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:

<style>
  body { 
    background-color: orange; 
    padding: 300px;
    text-align: center;
  }
</style>

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

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

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

But when you think about it, the entire internet and all web pages you ever visited are just big onclick events. You click here and you go there.

That’s all the internet really is.

And speaking of clicking and linking, check out the articles about how to refer to an external style sheet.

Until next time,
Will
Senior Developer Content Writer