Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to animate navbar on window scroll

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?

like image 785
Tomáš Roun Avatar asked Feb 11 '23 23:02

Tomáš Roun


1 Answers

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;
}
like image 142
Dejan.S Avatar answered Feb 14 '23 18:02

Dejan.S