JavaScript change image onClick event

In this blog post, we’re going to go over how to change the image on a link when it’s clicked. We’ll be using javascript and HTML.

This tutorial will cover the basics of what you need to know about JavaScript before starting with this topic.

JavaScript change image onClick event

1. What is the onclick event in JavaScript

The onclick property of the HTML DOM Event Object is used to execute code when an element is clicked. The code goes within curly brackets {} and should be placed inside a function. Example:

<button onclick="alert('hello world')">Get answers</button>

This will pop up “hello world” when you click this button.

2. How to change an image when you click it?

To begin, look at the code below and identify what changes when you click on a button:

<img src="" id="my_img"/><br />
<button onclick="changeImg()">Change Image!</button> 

So, the code is extremely simple and easy to understand! As you can see, we use a “button”. Inside of that button, we have placed an onclick event to call our changeImg function.

<script type="text/javascript">
	function changeImg() {                   
		var myImg = document.getElementById("my_img");
		var my_url = "images/1.jpeg";
		myImg.src = my_url; // Change img with this line  

Essentially all this does is make it so when the button is clicked, it will change the src (i.e., source) attribute which tells the page where to find your image.

This changes what shows up inside of your img tag (which was empty before). Then looks up an element with a certain ID, and sets its src to the file path of the image.

Final Word

In this post, we’ve discussed how to change an image onClick event in JavaScript. We hope that you find these tips helpful and are excited to see what you can make it do! Let us know if there is anything else we can help with as well-we would love to hear from you. Feel free to post a comment below or contact our team directly at your convenience.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment