JSFiddle - React, Tailwind, and code Playground
by Anton Kirichenko
July 19, 2020
HTML
<div class="wrapper">
<div class="box">
Here is some content.
</div>
<div class="box">
Here is some content.
</div>
<div class="box">
Here is some content.
</div>
<div class="box">
Here is some content.
</div>
<div class="box">
Here is some content.
</div>
</div>
CSS
body{
font-family: 'Anton', san-serif;
font-size: 40px;
}
.box{
height: 100vh;
margin: 2rem;
background: blue;
color:white;
display:flex;
align-items:center;
justify-content:center;
padding: 1rem;
text-align:center;
}
JavaScript
//Momentum Scrolling
const requestAnimationFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
const wrapper = document.querySelector(".wrapper"),
target = document.getElementsByTagName("body")[0];
let easing = "cubic-bezier(0.23, 1, 0.32, 1)",
duration = "1s",
lastScrollY = window.scrollY,
pos = 0;
const init = () => {
target.style.height = wrapper.offsetHeight + "px";
target.style.overflow = "auto";
wrapper.style.transition = "transform " + duration + " " + easing;
wrapper.style.position = "fixed";
wrapper.style.top = "0";
wrapper.style.left = "0";
wrapper.style.width = "100%";
wrapper.style.padding = "0";
wrapper.style.zIndex = "2";
wrapper.style.display = "block";
wrapper.style.backfaceVisibility = "hidden";
loop();
};
const onScroll = scrollY => {
pos = -(scrollY || document.documentElement.scrollTop);
wrapper.style.transform = "translateY(" + pos + "px)";
};
const loop = () => {
let scrollY = window.scrollY;
if (lastScrollY === scrollY) {
requestAnimationFrame(loop);
return;
} else {
lastScrollY = scrollY;
onScroll(scrollY);
requestAnimationFrame(loop);
}
};
init();