Skip to content
Advertisement

I need help to overwrite images on html page upon clicking a button [closed]

I have stored my images in an array called arr I have put a button on the html page called ‘Next’ so that whenever the user clicks the next button,the next image is picked up and overwrites the previous one the issue is the image on html page does not get overwritten by the next image( stored in the array),so how do I accomplish this

please help me as I am new to javascipt.

<body>
    <script>
        var arr = ["apple.jpg","kiwi.jpg", "pineapple.jpg","mango.jpg"];

        function a()
        {
            
            image5 = document.getElementById("image5");
            console.log(arr[0]);
            image5=new Image();
            image5.src = arr[0];
                 console.log("file is " + image5.src);
            arr.splice(0,1);
        }
    </script>
    <img src="apple.jpg" id="image5" style="width:300px;height:300px;">
    <button onClick="a();">Next</button>

</body>

Advertisement

Answer

I pretty much just cleaned up the code and had a variable that is the indicator to which picture comes up on the array and its loops. Also, I made the script tag defer so the tag loads after the whole page is so the function runs

<body>
    <script defer>
        var arr = ["apple.jpg","kiwi.jpg", "pineapple.jpg","mango.jpg"];
        var image5 = document.getElementById("image5");
        var i = 0;
        function a(){
            if(i>=4){i=0;}
            image5.src = arr[i];
            console.log("file is " + image5.src);
            i++;
        }
    </script>
    <img src="apple.jpg" id="image5" style="width:300px;height:300px;">
    <button onclick="a()">Next</button>
</body>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement