I wrote this simple carousel but without encapsulation. So previously I placed items from buttonControl() in global scope and added eventListeners on global scope, which are now emraced in prev() and next() functions. However, my encapsulation breaks the code. Because arguments from buttonControl() aren't global but prev() and next() needs them to work. I thought that maybe I can pass all arguments from buttonsControl() inside addEventListener('click', prev) but I cannot, because when I write thisaddEventListener('click', prev(slides,totalItems,allItems....)) it is launching this event without a click.And I even don't know if its correct way.
I thought of puting arguments from buttonsControl() inside prev() and next() but it won't work.
function buttonsControl(){
const slides = document.querySelector('.slides');
const totalItems = document.querySelectorAll('.slides>*').length - 1;
const allItems = document.querySelectorAll('.slides>*').length;
console.log(totalItems)
let activeItem = 0;
let controlCarouselFooter = document.querySelector('.carousel_footer');
controlCarouselFooter.innerHTML = `1 / ${allItems}`
console.log(controlCarouselFooter)
const prevButton = document.querySelector('.prev_button').addEventListener('click', prev)
const nextButton = document.querySelector('.next_button').addEventListener('click', next)
// no idea how to pass those arguments
}
// Buttons controls
function prev(){
// const prevButton = document.querySelector('.prev_button').addEventListener('click', () => {
if (activeItem === 0) {
activeItem = totalItems;
slides.style.transform = `translateX(-${totalItems * 100}%)`;
console.log(`if ${activeItem}`)
controlCarouselFooter.innerHTML = `${activeItem+1} / ${allItems}`
}else {
activeItem--;
slides.style.transform = `translateX(-${activeItem * 100}%)`;
console.log(`else ${activeItem}`)
controlCarouselFooter.innerHTML = `${activeItem+1} / ${allItems} `
}
}
// );
// }
function next(){
// const nextButton = document.querySelector('.next_button').addEventListener('click', () => {
if(activeItem < totalItems) {
activeItem++;
slides.style.transform = `translateX(-${activeItem * 100}%)`;
console.log(`if ${activeItem}`)
controlCarouselFooter.innerHTML = `${activeItem+1} / ${allItems}`
} else {
activeItem = 0;
slides.style.transform = 'none';
console.log(`else ${activeItem+1}`)
console.log(`totalItems ${totalItems}`)
controlCarouselFooter.innerHTML = `${activeItem+1} / ${allItems}`
}
}
// );
// };
// });
buttonsControl();