<div id="container">
<div id="box"></div>
<div id="content"></div>
</div>
<div id="display">0</div>
#container {
width: 300px;
height: 100px;
overflow-y: scroll;
position: relative;
border: 1px solid black;
}
#content {
height: 800px;
}
#box {
width: 20px;
height: 20px;
background: red;
position: absolute;
}
const container = document.getElementById('container');
const box = document.getElementById('box');
const display = document.getElementById('display');
let current = 0;
let target = 0;
container.addEventListener('scroll', () => {
target = container.scrollTop;
});
function lerp(start, end, t) {
return start + (end - start) * t;
}
function animate() {
current = lerp(current, target, 0.1);
box.style.top = current + 'px';
display.textContent = current;
requestAnimationFrame(animate);
}
animate();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.