I connected everything, checked everything, the script still does not work.

<script src="jquery-3.1.1.min.js"></script> <script src="script.js"></script> 

The script itself:

 $(document).ready(function() { if ($(document).scrollTop() > $('header').height() + 20) $('nav').addClass('fixed'); else $('nav').removeClass('fixed'); }); 

Styles:

 #nav.fixed { width: 100%; position: fixed; top: 0; opacity: 0.97; } 

What is the problem?

    1 answer 1

    You forgot here # (if nav is id , judging by the styles):

     $('#nav').addClass('fixed'); $('#nav').removeClass('fixed'); 

    Try also $(window).scrollTop() instead of $(document).scrollTop()

    You also need to put this in the Scroll event handler:

     $(window).scroll(function() { if ($(window).scrollTop() > $('header').height() + 20) $('#nav').addClass('fixed'); else $('#nav').removeClass('fixed'); }) 

      $(document).ready(function() { $(window).scroll(function() { if ($(window).scrollTop() > $('header').height() + 20) $('#nav').addClass('fixed'); else $('#nav').removeClass('fixed'); }) }); 
     #nav { color: #999; height: 50px; } body { height: 2000px } #nav.fixed { width: 100%; position: fixed; top: 0; opacity: 0.5; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header id="nav"> NAV </header> 

    • Fixed, it still does not work -
    • Try $(window).scrollTop() instead of $(document).scrollTop() - Crantisz
    • Again. Maybe there is no problem in the code. For here is a link to demonstrate the fixed menu. Artinblog.ru/uploads/posts/demo/jQuery/fiksirovannoje-menu.html And the script does not work for me here either - Anton
    • Updated the answer, look. - Crantisz
    • @ anton on the specified site in the script there is a line $(window).scroll(function() { , which adds (along with the rest of the code) the page scrolling event handler. Therefore, the function inside the site is called at each scroll. In your given in the code question, everything is executed only once, when loading the page. Be careful - Regent