Window.onscroll not working across pages

Hi all. I’m trying to get the navbar on my site to hide when the user scrolls down, and show when the user scrolls up. I have the custom code for this function

var prevScrollpos = window.pageYOffset;
var navbar = document.getElementById("navbar");

window.onscroll = function() {
  console.log("window scrolled");
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    navbar.style.top = "0";
  } else {
    navbar.style.top = -navbar.offsetHeight + "px";
  }
  prevScrollpos = currentScrollPos;
}

I want to apply it to every single page of the site, so I went to the site settings and pasted it in the Footer Code section.

However, it didn’t work. I tested it for a bit and it seemed like the whole window.onscroll function was not being executed.
Weirdly enough, if I apply the code to individual pages before </body> tag, or simply run it in the browser console, it’s working fine.

Any idea why I can’t apply the function to all pages in the site settings? Thanks!!


Here is my site Read-Only: LINK

I’m guessing your code is loading before it should. Try wrapping all of your JS in the following:

var Webflow = Webflow || [];
Webflow.push(function () {
    // YOUR CODE HERE
});

That solves the problem, thank you so much!

@Bowen_Shen - glad it worked. One thing I like to do and recommend instead of using the site-wide custom code is create a symbol of custom code that you can include on every page. It’s easier to maintain, edit, test, etc and I nest that inside my footer symbol so it ends up on every page I make.