Get Exact Scroll Position During OnScroll Tween
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();
const START = 0;
const MIDDLE = 200;
const END = 400;
const start = triggerRect.top - window.scrollY - MIDDLE;
const end = start + END;
const inSceneStart = scrollY => start <= scrollY;
const inSceneEnd = scrollY => end >= scrollY;
const updateTransform = value => {
tweens[0].style.transform = `translateX(${value}px)`;
tweens[1].style.transform = `translateY(${value}px)`;
}
const updateScroll = () => {
const scrollY = window.scrollY;
const pos = Math.min(400, Math.max(0, scrollY - start));
updateTransform(pos);
}
window.addEventListener('scroll', updateScroll, {passive: true});