I’m new to coding and would like to adapt a code I got from CodePen for my website.
It is to hover over an image and the images below will automatically cycle.
However this code works for only one set of images and doesn’t work if I have two sets of images.
I would really like to learn why please??? Thank you.
<html>
<style>
.js-animated figure.active {
opacity: 1;
}
.image-deck {
position: relative;
height: 12rem;
width: 18rem;
}
.image-deck figure {
opacity: 0;
height: 100%;
width: 100%;
position: absolute;
}
.image-deck figure img {
height: 100%;
width: 100%;
}
</style>
<body>
<!--Working-->
<div class="image-deck js-animated">
<figure>
<img src="https://picsum.photos/300/300">
</figure>
<figure>
<img src="https://picsum.photos/301/301">
</figure>
<figure>
<img src="https://picsum.photos/302/302">
</figure>
<figure>
<img src="https://picsum.photos/303/303">
</figure>
</div>
<!--Not Working-->
<div class="image-deck js-animated">
<figure>
<img src="https://picsum.photos/304/304">
</figure>
<figure>
<img src="https://picsum.photos/305/305">
</figure>
<figure>
<img src="https://picsum.photos/306/306">
</figure>
<figure>
<img src="https://picsum.photos/307/307">
</figure>
</div>
</body>
<script>
// get the image wrapper
const imageDeck = document.querySelector(".image-deck.js-animated");
// get the set of images within the wrapper
const images = imageDeck.children;
// reveal the first image
images[0].classList.add("active");
// set up the iterator
let i = 0;
// set up the function that we will call from our repeater
function cyclePhotos() {
// remove the active class from the current image
images[i].classList.remove("active");
// if the iterator is less than the total number of images
// go to the next number, otherwise reset to 0
i = i + 1 < images.length ? i + 1 : 0;
// add the active class to the next image
images[i].classList.add("active");
}
// instantiate the repeater
let repeater;
// when you hover over the image wrapper, start the reapeater
// repeat every 500ms
imageDeck.addEventListener("mouseover", (e) => {
repeater = setInterval(cyclePhotos, 500);
});
// when you are no longer hovering, clear the repeater
imageDeck.addEventListener("mouseout", (e) => {
clearInterval(repeater);
});
</script>
</html>