In this tutorial we will learn how to Toggle two images on click with JavaScript. JavaScript and HTML codes are give below.
Table of Contents
HTML Code
HTML Code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Toggle two images on click JavaScript</title>
</head>
<body>
<img src="car.png" id="image">
<br>
<button onclick="toggleImage()">Toggle Image</button>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code given below.
<script>
var x =0;
var img = document.getElementById('image');
function toggleImage(){
if(x==0)
{
img.src='bike.png';
x=1;
}
else
{
img.src='car.png';
x=0;
}
}
</script>
Video Tutorial
Watch video tutorial on How To Toggle two images on click with JavaScript.