In this tutorial we will learn How to Change image src on click with JavaScript. For this we can use the src property which allows us to change the image.
Table of Contents
src property
src property sets or returns the value of the src attribute.
It is used to define the address or URL of the image.
HTML Code
HTML Code is given below, in this code we have the img tag and a button tag with onclick event which will execute a function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Change image src on click JavaScript</title>
<style>
.responsive
{
width: 100%;
}
</style>
</head>
<body>
<img src="car.jpg" class="responsive" id='image'>
<button onclick="changeImage()">Change Image</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, user defined function changeImage() will be executed on click event of a button tag.
Inside this function, getElementById() method is used to select the image.
While src property will change it's src value.
<script>
function changeImage()
{
var img = document.getElementById('image');
img.src = 'bike.jpg';
}
</script>
We can also use setAttribute() method to change src of image.
<script>
function changeImage()
{
var img = document.getElementById('image');
img.setAttribute('src','bike.jpg');
}
</script>
Demo
Video Tutorial
Watch video tutorial on How to Change image src on click using JavaScript.