<div class="img-gallery-wrapper">
<div class="images-gallery">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
<img src="https://placehold.co/200x200" alt="" class="images">
</div>
<div class="images-gallery-btns">
<button class="next">Next</button>
<button class="prev">Previous</button>
</div>
</div>
// Mixins
@mixin flex-box-normal-style($js-content:center,$ali-content:center,$fl-direction:row) {
display:flex;
justify-content:$js-content;
align-content:$ali-content;
flex-direction:$fl-direction;
}
body {
@include flex-box-normal-style;
.img-gallery-wrapper {
width:200px;
.images-gallery {
border:1px solid black;
position:relative;
img {
display:none;
&.active {
display:block;
}
}
}
.images-gallery-btns {
@include flex-box-normal-style(center,center,row);
}
}
}
// get the dom element needed
let galleryLimit = document.querySelectorAll(".images-gallery img").length;
let galleryImg = document.querySelectorAll(".images-gallery img");
// set the first element active
galleryImg[0].classList.add("active");
//function for reseting the image all without no active class
function resetClassActive(){
galleryImg.forEach(function(item){
console.log("looping");
return item.classList.remove("active")
})
}
// closure function for next and prev btn
function manipulateGallery() {
let index = 0;
return function (action) {
if (action === "next" && index < galleryLimit) {
index++
return index
} else if (action === "prev" && index > 0) {
index--
return index;
}
};
}
let gallery = manipulateGallery();
// index for manipulating the current active img
let currentGlIndex;
document.querySelector(".prev").addEventListener("click", function () {
resetClassActive();
currentGlIndex = gallery("prev");
galleryImg[currentGlIndex].classList.add("active")
});
document.querySelector(".next").addEventListener("click", function () {
resetClassActive();
currentGlIndex= gallery("next");
galleryImg[currentGlIndex].classList.add("active")
});
Hello, guys! The code above is for a simple carousel. I used a closure function here. The issue is that when I click the ‘next’ button, the index increments until it becomes greater than the gallery’s item limit. The same thing happens when I decrement it.
here is the code in : codepen