Swap images in JavaScript | Simple onclick image swap Example

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:

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:

Swap images in JavaScript

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.