so this function is basically when i click on myBtn the img change to another img, i made that but how can i add another img i wanna change and change both the imgs when i click, can anyone help
const myBtn = document.getElementById("darktheme");
const img = document.getElementById("ferrarijs")
let mySrc = img.getAttribute("src");
let counter = 0;
myBtn.addEventListener("click", function() {
if (counter % 2 === 0) {
img.setAttribute("src", "images/ferrari.jpg");
} else {
img.setAttribute("src", "images/ferrariwhte.jpg");
}
counter++;
});
3
Answers
It’s pretty easy. That’s just copy & paste & you’re done.
This will toggle the src of
<img src="teslawhite.jpg" src="teslajs">
betweentesla
&teslawhite
. I know "Tesla" is a pretty dumb example. Feel free to change it with what you want.You can use
querySelectorAll
to find all<img>
‘s.Then loop over those to set the
src
.Use an array to get the next image
src
, check if the current index matcheslength - 1
, if so, start again at index 0You will need to compute the next index by using the length of an image URL array.