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.
JavaScript
x
20
20
1
<body>
2
<script>
3
var arr = ["apple.jpg","kiwi.jpg", "pineapple.jpg","mango.jpg"];
4
5
function a()
6
{
7
8
image5 = document.getElementById("image5");
9
console.log(arr[0]);
10
image5=new Image();
11
image5.src = arr[0];
12
console.log("file is " + image5.src);
13
arr.splice(0,1);
14
}
15
</script>
16
<img src="apple.jpg" id="image5" style="width:300px;height:300px;">
17
<button onClick="a();">Next</button>
18
19
</body>
20
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
JavaScript
1
16
16
1
<body>
2
<script defer>
3
var arr = ["apple.jpg","kiwi.jpg", "pineapple.jpg","mango.jpg"];
4
var image5 = document.getElementById("image5");
5
var i = 0;
6
function a(){
7
if(i>=4){i=0;}
8
image5.src = arr[i];
9
console.log("file is " + image5.src);
10
i++;
11
}
12
</script>
13
<img src="apple.jpg" id="image5" style="width:300px;height:300px;">
14
<button onclick="a()">Next</button>
15
</body>
16