How to swap images in JavaScript?
You can use the image id and getElementById method to change or swap images by click on a button or itself on images in JavaScript.
document.getElementById('imgID').src = "newImage.png"
Must Read:
- Dynamically set image src using JavaScript
- JavaScript get image source from img tag
- Change image src using JavaScript
Example of JavaScript functions Swapping Images onclick
HTML example code to change the image on click on it. Swapping two images abc.png and xyz.png in JavaScript:-
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function swapImage(){
if (document.getElementById("pic").src.endsWith('abc.png') == true) //Comparison
{
document.getElementById("pic").src = "xyz.png"; //assignment
}
else if (document.getElementById("pic").src.endsWith('xyz.png') == true)
{
document.getElementById("pic").src = "abc.png";
}
}
</script>
<img src="abc.png" id="pic" onclick="swapImage()"/>
</body>
</html>
Output:
Do comment if you have any other examples or have doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version