I'd like to ask if there is a way to use jQuery animate() method to animate horizontal navbar's top property on window scroll.
Here is code I use:
window.addEventListener("scroll", function() {
if (window.scrollY > 200) {
$('#navbar').css({top:"100px"});
}
else {
$('#navbar').css({top:"0px"});
}
},false);
CSS:
#navbar{
top:0;
position:fixed;
transition: top 0.5s;
}
When you scroll down 200px the navbar changes its top position from 0 to 100px; This works fine, but if I change methods and put .animate instead of .css,
$('#navbar').animate({top:"100px"});
it stops working. Any ideas why?
You can do this with css transition
and how you can achieve this is with jQuery addClass
instead of css()
DEMO
$(window).on('scroll', function () {
if ($(this).scrollTop() > 200) {
if (!$('.navbar').hasClass('expand')) {
$('.navbar').addClass('expand');
}
} else {
if ($('.navbar').hasClass('expand')) {
$('.navbar').removeClass('expand');
}
}
});
.navbar {
top: 0;
position: fixed;
transition: top 0.5s;
}
.navbar.expand {
top: 100px;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With