Get Exact Scroll Position During OnScroll Tween
by wamosjk
HTML
<h1>Scroll Down</h1>
<div class="wrapper">
<div class="line start trigger"></div>
<div class="line end"></div>
<div class="tween left"></div>
<div class="tween right"></div>
</div>
CSS
.wrapper{
position:relative;
margin: 100vh 20px;
background: rgb(240,240,240);
height: 900px;
}
.line{
position:absolute;
left: 0;
width: 100%;
height: 1px;
background: red;
}
.start{
top: 200px;
}
.end{
bottom: 200px;
}
.tween{
position:absolute;
top:200px;
width: 100px;
height: 100px;
background: blue;
}
.left{
left: 0;
}
.right{
right: 0;
}
JavaScript
const tweens = document.querySelectorAll('.tween');
const trigger = document.querySelector('.start');
const triggerRect = trigger.getBoundingClientRect();
let yScroll = window.scrollY;
let yCurrent = yScroll;
let AF = null;
const start = triggerRect.top - yScroll - 200;
const end = start + 400;
const updateScroll = () => {
yScroll = window.scrollY;
startAnimation();
}
const startAnimation = () => {
if(!AF) AF = requestAnimationFrame(animate)
}
const cancelAnimation = () => {
yCurrent = yScroll;
cancelAnimationFrame(AF);
AF = null;
}
const animate = () => {
if(yCurrent === yScroll) cancelAnimation();
else {
updateElements();
yCurrent = yScroll;
AF = requestAnimationFrame(animate);
}
}
const updateElements = () => {
const pos = yCurrent - start;
if(inScene()){
tweens[0].style.transform = `translateX(${pos}px)`;
tweens[1].style.transform = `translateY(${pos}px)`;
}
}
const inScene = () => {
return start <= yCurrent && end >= yCurrent ? true : false;
};
window.addEventListener('scroll', updateScroll);