1

I have a very simple navbar that changes on scroll. The logo is supposed to be prepended and it does but every time the page is scrolled it adds another logo. I have a boolean in there to check whether the logo has been added but it still runs the code anyway. Here is my code:

$(window).scroll(function() {
        var scroll = $(window).scrollTop(),
            hidden = true;
        if (scroll >= 470) {
            $('#nav').addClass('static-nav');
            if(hidden) {
                $('#logo').prepend(' <div class="logo-container"> <img src="img/logo3.png" alt="logo"></div>');
                hidden= false;
            }
        }else{
            $('#nav').removeClass('static-nav');
            if(!hidden) {
                $('.logo-container').remove();
                hidden = true;
            }
        }
    });
Grant Jordan
  • 408
  • 6
  • 18
  • 3
    You are setting `hidden = true;` on each scroll handler call – A. Wolff Feb 22 '16 at 10:12
  • but your boolean is reset each time you enter the function. Maybe you could simply check if the class "logo-container" is there or not. It doesn't make any sense to use that hidden boolean, unless you assign it like `hidden = $('.logo-container').length === 0` – Icepickle Feb 22 '16 at 10:13
  • @A.Wolff That was it. Thank you so much. – Grant Jordan Feb 22 '16 at 10:15

1 Answers1

0

The hidden bool should be outside of the scroll event function, or it will be true every time you change your scroll position.

But you should check to see if the nav is visible instead, not go by pixels to the top. You cannot predict if the user will see the menu that way or not. Something like this should work:

How to tell if a DOM element is visible in the current viewport?

Community
  • 1
  • 1
Tony Gustafsson
  • 736
  • 6
  • 16