Are you looking to create an element that stays visible in the viewport while also having a scrolling animation effect?
It can be quite amusing!
To achieve this, the element needs to have its position set to absolute
so it follows the document's scrollTop
position. Using fixed
for positioning ties the element to the viewport.
However, implementing an animation on scroll can be tricky. The scroll
event fires rapidly and queuing animations for every scroll event will lead to a chaotic display. To address this, you can use a flag to check if the animation has already been triggered by a previous scroll event and prevent further triggers.
Additionally, adding a delay after scrolling ends can help ensure the animation runs smoothly. My suggestion is a 400ms delay paired with a fast 100ms animation duration. This combination enhances user experience and minimizes discrepancies in the final position due to continued scrolling.
While not flawless, it offers a functional solution.
$(function() {
// Flag variable
scrolling = false;
// Variable to store scrollTop position
var top;
// Scroll handler
$(window).on('scroll', function() {
// Update top position on scroll
top = $(this).scrollTop() + 10;
// Prevent further execution until current animation finishes
if (scrolling) {
return;
}
// User is scrolling
scrolling = true;
// Delay before initiating animation
setTimeout(function() {
// Animate!
$('#lan').animate({
top: top + 'px'
}, 100, function() {
scrolling = false;
});
}, 400);
});
});
body {
min-height: 2000px
}
#lan {
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lan">My First Dangerous</div>