Could someone help me with a horizontal infinite scroll? I followed a tutorial for a vertical infinite scroll (and after previously asking a question on StackOverflow), I managed to get the Javascript working without any errors appearing in the console. However, it doesn't work horizontally. I thought I would need to change the .scrollTop
and .offsetHeight
to be .scrollLeft
and .offsetWidth
but then it stops working.
I can get the code working to make the carousel scroll infinitely vertically if I swap in .scrollTop
and .offsetHeight
Just not horizontally. I would be really grateful for any help to fix this. Thanks.
var infiniteScroll = document.querySelector(".infinite-scroll");
var infiniteScrollItems = document.querySelectorAll(".infinite-scroll .iscroll-item");
let clones = [];
let disableScroll = false;
let infiniteScrollWidth = 0;
let scrollPosition = 0;
let clonesWidth = 0;
function getScrollPosition() {
return infiniteScroll. scrollLeft;
}
function setScrollPosition(pos) {
infiniteScroll.scrollLeft = pos;
}
function getClonesWidth() {
clonesWidth = 0;
clones.forEach(clone => {
clonesWidth += clone.offsetWidth;
});
return clonesWidth;
}
function reCalc() {
scrollPosition = getScrollPosition();
infiniteScrollWidth = infiniteScroll.scrollWidth;
clonesWidth = getClonesWidth();
if(scrollPosition <= 0) {
setScrollPosition(1);
}
}
function scrollUpdate() {
if(!disableScroll) {
scrollPosition = getScrollPosition();
if(clonesWidth + scrollPosition >= infiniteScrollWidth) {
setScrollPosition(1);
disableScroll = true;
}
else if (scrollPosition <= 0) {
setScrollPosition(infiniteScrollWidth - clonesWidth);
disableScroll = true;
}
}
if(disableScroll) {
window.setTimeout(() => {
disableScroll = false;
}, 40);
}
}
function onLoad() {
infiniteScrollItems.forEach(ScrollItem => {
const cloneItems = ScrollItem.cloneNode(true);
infiniteScroll.appendChild(cloneItems);
cloneItems.classList.add('js-clone');
});
clones = infiniteScroll.querySelectorAll('.js-clones');
reCalc();
infiniteScroll.addEventListener('scroll', () => {
window.requestAnimationFrame(scrollUpdate);
}, false);
window.addEventListener('resize', () => {
window.requestAnimationFrame(reCalc);
}, false);
}
window.onload = onLoad();