I'm trying to do a simple animation where an image changes from A to B to C on the click of a button. I'm getting stuck at Cannot read properties of undefined (reading 'classList'), but I can't figure out what I did wrong; I used a similar structure for a carousel without any issues.
I'm just trying to change the elements from "seed" to Bootstrap's ".d-none".
var javaButton = document.getElementById("button-trigger");
const track = document.querySelector(".plant-wrapper");
const slides = Array.from(track.children);
const targetIndex = slides.findIndex;
const hidden = document.querySelector(".d-none");
const seeds = document.querySelector(".seed");
javaButton.addEventListener("click", moveToSlide);
function moveToSlide(slides, seeds, hidden, targetIndex) {
if (targetIndex === 0) {
seeds.classList.add("is-hidden");
hidden.classList.remove("is-hidden");
} else if (targetIndex === slides.length - 1) {
seeds.classList.remove("is-hidden");
hidden.classList.add("is-hidden");
} else {
seeds.classList.remove("is-hidden");
hidden.classList.remove("is-hidden");
}
};
<button type="button" id="button-trigger">Check it out!</button>
<div class="plant-wrapper">
<img src="images/seed.png" class="seed mx-auto d-block" id="seed1">
<img src="images/sprout.png" class="mx-auto d-block d-none" id="seed2">
<img src="images/stem.png" class="mx-auto d-block d-none" id="seed3">
<img src="images/pot.png" class="pot mx-auto d-block">
</div>
Problem is that you do not pass arguments to moveToSlide function
You can solve removing arguments of moveToSlide function (function will read variables declared above)
function moveToSlide() {
// Code...
}
Or passing values to function (best option)
javaButton.addEventListener("click", () => moveToSlide(slides, seeds, hidden, targetIndex))
If your ultimate goal is to create a slider, there's a better way to do it.
w3schools have a demo of it: https://www.w3schools.com/howto/howto_js_slideshow.asp
Here is my way to make a slider:
index.html
<button type="button" id="button-trigger" onclick="changeImg()">Check it out!</button>
<div class="plant-wrapper" id="plant-wrapper">
</div>
index.js
var index = 0;
const imageArray = [
"images/1.png",
"images/2.png",
"images/3.png",
"images/4.png"
];
function changeImg(){
(index == imageArray.length - 1 ? index = 0 : index++);
showImage();
}
function showImage(){
document.getElementById("plant-wrapper").innerHTML = '<img src="' + imageArray[index] + '" class="mx-auto" />';
}
window.onload = function() {
showImage()
}