My webpage has a very long layout with text in one column and a floating element in another. I want the floating element to follow the scroll of the window and return to its original offset once scrolling stops.
The current code I have is:
var ticking = false;
var box = document.getElementById('box1');
window.addEventListener('scroll', function() {
ticking = ticking || requestAnimationFrame(function() {
ticking = false;
var top = window.scrollY;
console.log(top);
box.style.transform = 'translateY(' + top + 'px)';
box.style.transition = 'all 100ms ease-out';
});
});
#left {
width: 200px;
margin: 50px;
position: relative;
float: left;
}
#right {
float: left;
width: 800px;
font-size: 200%;
}
#box1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 50px;
}
<div class="outer">
<div id="left">
<div id="box1"></div>
</div>
<div id="right">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...[truncated for brevity]
Visit my Codepen page for reference
However, I am experiencing flickering of the element during scrolling. This might be due to frequent modifications of transform: translateY()
. Is it possible to introduce a delay similar to setTimeout()
or setInterval()
? Alternatively, is there a better approach to achieve this effect? If not, can anything be done to reduce the flickering?