Skip to content

Instantly share code, notes, and snippets.

@lincolnlemos
Created September 13, 2018 19:06
Show Gist options
  • Save lincolnlemos/1f28def958ea72faea295c9a709aa5f6 to your computer and use it in GitHub Desktop.
Save lincolnlemos/1f28def958ea72faea295c9a709aa5f6 to your computer and use it in GitHub Desktop.
GSAP SmoothScroll
<div class="viewport">
<div id="scroll-container">
<!-- content -->
</div> <!-- #scroll-container -->
</div> <!-- .view-port -->
/** Parallax **/
let html = document.documentElement;
let body = document.body;
let scroller = {
target: document.querySelector('#scroll-container'),
ease: 0.05, // <= scroll speed
endY: 0,
y: 0,
resizeRequest: 1,
scrollRequest: 0,
};
let requestId = null;
Set default attributes to scroller
TweenLite.set(scroller.target, {rotation: 0.01, force3D: true});
window.addEventListener('load', onLoad);
function onLoad() {
updateScroller();
window.focus();
window.addEventListener('resize', onResize);
document.addEventListener('scroll', onScroll);
}
function updateScroller() {
let resized = scroller.resizeRequest > 0;
if (resized) {
let height = scroller.target.clientHeight;
body.style.height = height + 'px';
scroller.resizeRequest = 0;
}
let scrollY = window.pageYOffset || html.scrollTop || body.scrollTop || 0;
scroller.endY = scrollY;
scroller.y += (scrollY - scroller.y) * scroller.ease;
if (Math.abs(scrollY - scroller.y) < 0.05 || resized) {
scroller.y = scrollY;
scroller.scrollRequest = 0;
}
TweenLite.set(scroller.target, {
y: -scroller.y,
});
requestId = scroller.scrollRequest > 0 ? requestAnimationFrame(updateScroller) : null;
}
function onScroll() {
scroller.scrollRequest++;
if (!requestId) {
requestId = requestAnimationFrame(updateScroller);
}
}
function onResize() {
scroller.resizeRequest++;
if (!requestId) {
requestId = requestAnimationFrame(updateScroller);
}
}
/** Parallax **/
body {
overflow-x: hidden;
overflow-y: scroll;
}
.viewport {
overflow: hidden;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#scroll-container {
position: absolute;
overflow: hidden;
z-index: 10;
display: flex;
justify-content: center;
backface-visibility: hidden;
transform-style: preserve-3d;
flex-direction: column;
width: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment