Trying to switch between images with a single button using JavaScript
07:30 28 Jan 2026

I am trying to switch between 2 images with a single button, with the intention of adding more images.

I click on the button it changes to image2.jpg but when I click again it doesn't change back to image1.jpg (image1.jpg being the initial image).

HTML:

pic

insert 1st text here

insert 2nd text here

insert 3rd text here

JavaScript:

const current__img = document.getElementById("enrollment__img1");

function changeimage() {
  var image1 = "Images/image1.jpg";
  var image2 = "Images/image2.jpg";
  if (current__img.src != image1) {
    current__img.src = image2;
  } else {
    current__img.src = image1;
  }   
}  

I've also tried:

const current__img = document.getElementById("enrollment__img1");

function changeimage() {
  var firstcounter = 0 ;
  var image1 = "Images/image1.jpg";
  var image2 = "Images/image2.jpg";
  if (firstcounter == 0) {
    current__img.src = image2;
    firstcounter++;
  } else {
    firstcounter--;
    current__img.src = image1;
  }   
}
javascript html