-1

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?

$(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..

Amorandron
  • 13
  • 2
  • @Santi The code posted here is absolutely not an MCVE. There is no markup for it to operate on, and no way for us to actually run the code to reproduce the problem. – user229044 Oct 17 '16 at 18:07
  • I suppose, I guess I just feel that a flag and the original complaint may have been satisfactory, without the need for a second snarky "PHPBB" comment. – Tyler Roper Oct 17 '16 at 18:09
  • @Amorandron - see this - http://stackoverflow.com/a/3464890/104380 – vsync Oct 17 '16 at 18:11
  • you should use `css` to do these transitions, and add a class for "on" state, to have the opacity transitioned using `opacity:1; transition:.3s` for example – vsync Oct 17 '16 at 18:12
  • Add a CSS transition to #topnav, and instead of using animate(), use another css() to change the opacity to 1. Also fix the sintax on css(): CSS: #topnav{ opacity:0; transition: .3s;} css(): $("#topnav").css("opacity", "0"); – Bruno García Oct 17 '16 at 18:14

1 Answers1

0

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});
        }
})
Pat
  • 2,540
  • 1
  • 21
  • 28