I'm working on a navigation bar that sticks to the top of the page. As the user scrolls down, I want the bar to shrink, and when they scroll back up, it should return to its original size.
Issue: The problem I'm facing is that when the user quickly scrolls back to the top of the page, the navbar remains shrunk, and there's a delay in triggering the animate()
function within the scrollTop()
callback function.
To troubleshoot this, I added
console.log($(window).scrollTop());
to track the user's position on the page. This logs the position instantly as the user scrolls. However, {console.log('animated');
which should fire after the animation completes, only appears a few seconds later after console.log($(window).scrollTop());
shows 0
.
How can I make the animate()
function respond promptly when the user scrolls up?
JavaScript Code
var navBar = $('#navbar-inner');
var top = navBar.css('top');
$(window).scroll(function() {
console.log($(window).scrollTop());
if($(this).scrollTop() > 50) {
navBar.animate({'marginTop':'-20', 'height':'60'}, 300);
} else {
navBar.animate({'marginTop':'0', 'height':'80'}, 300, function()
{console.log('animated');});
}
});