JavaScript > Dealing with HTML Controls

Changing of images in JavaScript

How to change image source using JavaScript?


In case we want to change the images in JavaScript, we can follow this approach.

<h1>Changing the Image</h1>
    <img src="waterbottel.gif" id="myImage" width="100" height="150">
    <input type="button" onclick="changeImage()" value="Change" />
    <p>Click on the "Change" button to convert waterbottle<br />
        into Softdrink bottle</p>

    <script>
        function changeImage() {
            var image = document.getElementById('myImage');
            if (image.src.match("colorbottel")) {
                image.src = "waterbottel.gif";
            }
            else {
                image.src = "colorbottel.gif";
            }
        }
    </script>

In the above code snippet, getElementById finds a image with id “myImage” and changes the image by each click on "Change" button. In the <script> code  image.src.match() attribute is used in this .match() tests if image.src contains the string "colorbottel". If there is match, .match() changes image.src to "waterbottel".

OUTPUT

Onclick of "Change" button in the above output wil change the water bottlel into Softdrink bottle, that can be shown in the below image.

 Views: 116525 | Post Order: 60



Write for us






Hosting Recommendations