Amorandron Amorandron - 1 month ago 9
CSS Question

jQuery not updating my page

I am creating this website for a school project of mine.

I want to have a navbar that automatically shows up when you are not on the top of the page, that is working; the thing is when I scroll back to the top nothing changes. Could somebody look at my code and tell me what I need to change or update? Thanks in advance!



$(document).ready(function() {
$(window).scroll(function() {
console.log($(window).scrollTop());
if ($(window).scrollTop() != 0) {
$("#topnav").animate({
opacity: 1
}, 300);
} else if ($(window).scrollTop() == 0) {
console.log("done");
$("#topnav").css({
opacity: 0
});
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





The
console
does give me a return, yet the page does not seem to change.. I can't figure out why!

Pat Pat
Answer

I think

if ($(window).scrollTop() != 0) {
   $("#topnav").animate({opacity: 1}, 300);
}

is queuing a LOT of animations on #topnav and so trying to change the element mid animation won't have an effect.

You can set a flag to see ensure the animation is limited to one time. For example:

var flag = false;

$(window).scroll(function(){
    if ($(window).scrollTop() != 0) {
        if(!flag){
            $("#topnav").animate({opacity: 1}, 300, function(){
              flag = false;
            });
              flag = true;
            }
        }
        else if ($(window).scrollTop() == 0) {
            console.log("done");
            $("#topnav").css({opacity: 0});
        }
})