How to animate navbar on window scroll

I would like to ask if there is a way to use the jQuery animate () method to animate the horizontal navbar top property while scrolling the window.

Here is the code I'm using:

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 200px, the navigation bar changes its top position from 0 to 100 pixels; This works fine, but if I change the methods and put .animate instead of .css,

$('#navbar').animate({top:"100px"});    

he stops working. Any ideas why?

+4
source share
2 answers

You can do this with css transition, and how can you achieve this, use jQuery addClassinsteadcss()

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;
}
+7
source

All Articles