logo

Example of Implementing Multiple Image Toggle Functionality in JavaScript 📂Programing

Example of Implementing Multiple Image Toggle Functionality in JavaScript

Showcase

A toggle refers to a feature that can switch between two or more states or options1. In the example above, pressing the buttons changes the image as follows:

  • A: Pikachu
  • B: Bulbasaur
  • C: Charmander
  • D: Squirtle

Code

HTML

<button onclick="toggle_A()">A</button>
<button onclick="toggle_B()">B</button>
<button onclick="toggle_C()">C</button>
<button onclick="toggle_D()">D</button>

<img id="img" src="A.webp" width="280px" frameborder="0"></img>
  • button onclick="toggle_*()": Specifies the JavaScript function that will respond to the button.
  • img id="img" src="A.webp": Specifies the id of the image that will be changed by JavaScript. Here, src="A.webp" means that A.webp is used as the default image when nothing is selected.

JavaScript

<script>
function toggle_A() {document.getElementById("img").src = "A.webp";}
function toggle_B() {document.getElementById("img").src = "B.webp";}
function toggle_C() {document.getElementById("img").src = "C.webp";}
function toggle_D() {document.getElementById("img").src = "D.webp";}
</script>
  • getElementById("img").src = "A.webp": Changes the src attribute of the element with id “img” to “A.webp”. In other words, when the button is clicked, the image switches to the corresponding file.