Changing Images (src)
JavaScript can change the picture shown in an <img> element by updating its src attribute.
Example
<img id="animal" src="cat.png">
<script>
let pic = document.getElementById("animal");
pic.src = "dog.png"; // switch image
</script>
(Make sure the image files exist on your site.)
You can trigger the change inside a function:
<img id="animal" src="cat.png">
<button onclick="switchPic()">Switch</button>
<script>
let pic = document.getElementById("animal");
function switchPic(){
pic.src = "dog.png";
}
</script>
Natural Next Questions
You might be wondering:
- How can I make one button toggle between two pictures?
- How can I cycle through several pictures like a slideshow?
- How can I make “Next” and “Previous” buttons to move through pictures?
More on changing HTML attributes with JavaScript:
W3Schools – JavaScript HTML DOM (Change Attributes)
This page was tweaked with the help of ChatGPT. But the original was pretty good already. 😉