Infinite Continuous Looping Scroll On Mobile
I have a small problem with my looping scroll. It works pretty well on larger displays, but on handheld devices it glitches quite a lot. I'm not sure where I'm doing something wron
Solution 1:
Got it to work based on this codepen: https://codepen.io/vincentorback/pen/zxRyzj
Sharing it here as well if somebody finds it useful:
<style>html,
body {
height: 100%;
overflow: hidden;
}
.infinite {
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.clone {
height: 50vw;
}
</style><script>var doc = window.document,
context = doc.querySelector('.infinite'),
clones = context.querySelectorAll('.clone'),
disableScroll = false,
scrollHeight = 0,
scrollPos = 0,
clonesHeight = 0,
i = 0;
functiongetScrollPos () {
return (context.pageYOffset || context.scrollTop) - (context.clientTop || 0);
}
functionsetScrollPos (pos) {
context.scrollTop = pos;
}
functiongetClonesHeight () {
clonesHeight = 0;
for (i = 0; i < clones.length; i += 1) {
clonesHeight = clonesHeight + clones[i].offsetHeight;
}
return clonesHeight;
}
functionreCalc () {
scrollPos = getScrollPos();
scrollHeight = context.scrollHeight;
clonesHeight = getClonesHeight();
if (scrollPos <= 0) {
setScrollPos(1); // Scroll 1 pixel to allow upwards scrolling
}
}
functionscrollUpdate () {
if (!disableScroll) {
scrollPos = getScrollPos();
if (clonesHeight + scrollPos >= scrollHeight) {
// Scroll to the top when you’ve reached the bottomsetScrollPos(1); // Scroll down 1 pixel to allow upwards scrolling
disableScroll = true;
} elseif (scrollPos <= 0) {
// Scroll to the bottom when you reach the topsetScrollPos(scrollHeight - clonesHeight);
disableScroll = true;
}
}
if (disableScroll) {
// Disable scroll-jumping for a short time to avoid flickeringwindow.setTimeout(function () {
disableScroll = false;
}, 40);
}
}
functioninit () {
reCalc();
context.addEventListener('scroll', function () {
window.requestAnimationFrame(scrollUpdate);
}, false);
window.addEventListener('resize', function () {
window.requestAnimationFrame(reCalc);
}, false);
}
if (document.readyState !== 'loading') {
init()
} else {
doc.addEventListener('DOMContentLoaded', init, false)
}
</script>
Post a Comment for "Infinite Continuous Looping Scroll On Mobile"