Window.OnScroll

Happy New Year!

I’m working on incorporating a bit of JS, but it’s not getting triggered, any pointers on what I might be doing incorrectly. I was following this example from W3School. I’m wondering if it is something with the call to the ‘window’ and the structure of blocs.

I’ve got multiple blocs with a div class of ‘content’ and one bloc with an element id of ‘navbar’.

Thanks!

<script>
   window.onscroll = function() {myFunction()};

    var navbar = document.getElementById("navbar");

    var sticky = navbar.offsetTop;

    function myFunction() {
      if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky")
      } else {
        navbar.classList.remove("sticky");
      }
    }
    </script>

Only the first element after the navbar needs the content class. As it uses this to add padding when the navbar becomes sticky, other wise the content jumps.

Blocs 4 sticky option on the navbar now does a scroll to sticky - so if you can just use this.

Other-wise if you still need to use the other approach, make sure the script is in the page footer. And I assume you have added the CSS to the page header?

Thanks for the pointer for the sticky option! Having it in the footer was the missing piece… good to know. Appreciate your help!

1 Like