G
G
gipsonsuro2021-03-15 14:25:37
Slider
gipsonsuro, 2021-03-15 14:25:37

How to make multiple slider carousels on one page?

Hello!
Help me understand, there is a carousel slider on the page, I like it, simple, nothing more, I wanted to make another same slider with different content, but the scroll buttons do not work on the second slider. I tried to register via ID , but it didn’t work out, the buttons work on one slider, but not on the other.

Script:

const testimonials = document.querySelector('.testimonials');
const scroller = testimonials.querySelector('.scroller');
const nextBtn = testimonials.querySelector('.btn.next');
const prevBtn = testimonials.querySelector('.btn.prev');
const itemWidth = testimonials.querySelector('.item').clientWidth;

nextBtn.addEventListener('click', scrollToNextItem);
prevBtn.addEventListener('click', scrollToPrevItem);

function scrollToNextItem() {
if(scroller.scrollLeft < (scroller.scrollWidth - itemWidth))
// The scroll position is not at the beginning of last item
scroller.scrollBy({left: itemWidth, top: 0, behavior:'smooth' });
else
// Last item reached. Go back to first item by setting scroll position to 0
scroller.scrollTo({left: 0, top: 0, behavior:'smooth'});
}
function scrollToPrevItem() {
if(scroller.scrollLeft != 0)
// The scroll position is not at the beginning of the first item
scroller. scrollBy({left: -itemWidth, top: 0, behavior:'smooth'});
else
// This is the first item. Go to last item by setting scroll position to scroller width
scroller.scrollTo({left: scroller.scrollWidth, top: 0, behavior:'smooth'});
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question