Trying to switch between images with a single button using JavaScript [duplicate]

6 days ago 7
ARTICLE AD BOX

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:

<Div class="main"> <div class="main__container"> <div class="main_content"> <img src="Images/image1.jpg" alt="pic" class="enrollment__img" id="enrollment__img1"> <button id="clickme" onclick="changeimage()">click me</button> <h1>insert 1st text here</h1> <h2>insert 2nd text here</h2> <h3>insert 3rd text here</h3> </div> </div> </Div>

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; } }

Mister Jojo's user avatar

Mister Jojo

23k6 gold badges28 silver badges46 bronze badges

Seph's user avatar

New contributor

Seph is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

4

Read Entire Article