To allow infinite scrolling inside a <div>, I added a 'scroll' event to it. When the first child is in the viewport, I prepend the last child and viceversa.
Ive gotten this to work perfectly until I bring in scroll-snap-align. Here, I have set up an example where one carousel has scroll snap while the other one doesn't.
const scrollInfo = (parent) => {
let viewWidth = parseInt(getComputedStyle(parent).width),
realWidth = parent.scrollWidth - viewWidth,
currentChild = Math.floor((parent.scrollLeft + viewWidth / 3) / viewWidth);
return {
current: currentChild,
view: viewWidth
};
};
let carousels = [infiniteCarousel1, infiniteCarousel2]
carousels.forEach(carousel => {
carousel.onscroll = () => {
let info = scrollInfo(carousel),
scroll = carousel.scrollLeft,
len = carousel.children.length - 1;
if (info.current <= 0) {
carousel.scrollLeft = scroll + info.view;
carousel.prepend(carousel.children[len]);
} else if (info.current >= len) {
carousel.scrollLeft = scroll - info.view;
carousel.append(carousel.children[0]);
}
};
window.addEventListener("DOMContentLoaded", () => {
setTimeout(() => {
carousel.scrollTo({ left: scrollInfo(carousel).view });
}, 1000);
})
})
* {
box-sizing: border-box;
}
.carousel {
display: flex;
overflow-x: scroll;
width: 100%;
height: 100px;
}
.carousel > div {
display: inherit;
justify-content: center;
align-items: center;
min-width: 100%;
height: 100%;
border: 2px solid;
scroll-snap-align: center;
}
#infiniteCarousel1 {
scroll-snap-type: x mandatory;
}
<h2>Scroll Snap</h2>
<div id="infiniteCarousel1" class="carousel">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<h2>No Scroll Snap</h2>
<div id="infiniteCarousel2" class="carousel">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
The same example in CodePen.
I will tell you a trick i used in the past. Add an extra slide of the last slide to the beginning and an extra slide of the first slide on the end. Then when the selected slide its either of those 2. Scroll to position of the original without animation. Let me know of you need more help.