You’ll want to visit this page first:
Changing Images page
1. Toggle between two pictures
One button switches back and forth between two images.
<img id="animal" src="cat.png">
<button onclick="togglePic()">Toggle</button>
<script>
let pic = document.getElementById("animal");
let toggle = 0;
function togglePic(){
toggle = 1 - toggle; // flips 0 <-> 1
if (toggle === 0){
pic.src = "cat.png";
} else {
pic.src = "dog.png";
}
}
</script>
2. Cycle through several pictures (slideshow)
Each click moves to the next picture in the list and loops back to the start.
<img id="animal" src="cat.png">
<button onclick="nextPic()">Next</button>
<script>
let pic = document.getElementById("animal");
let pics = ["cat.png", "dog.png", "bird.png"];
let index = 0;
function nextPic(){
index = index + 1;
if (index === pics.length){
index = 0;
}
pic.src = pics[index];
}
</script>
3. Next and Previous buttons
Two buttons let the user move forward or backward through the pictures.
<img id="animal" src="cat.png">
<button onclick="prevPic()">Previous</button>
<button onclick="nextPic()">Next</button>
<script>
let pic = document.getElementById("animal");
let pics = ["cat.png", "dog.png", "bird.png"];
let index = 0;
function nextPic(){
index = index + 1;
if (index === pics.length){
index = 0;
}
pic.src = pics[index];
}
function prevPic(){
index = index - 1;
if (index < 0){
index = pics.length - 1;
}
pic.src = pics[index];
}
</script>
This page was created by ChatGPT with the guidance, editorial scrutiny, and approval of the human creator of this website.