Change Navbar Colour on Scroll

I have a navbar that I want to make transparent on an image on initial page load. When the page is scrolled, I would like the navbar color to change to white.
I have read a few comments in this forum on it, but I have not been successful in implementing this.
Is there anyone who might be able to help me with this?

Step one:

Add a navbar component, set Position to Fixed to top and Background to Default
image

Set the ID of the navbar to main-nav
image

Step two - create a javascript file and add the following:

(function () {
    "use strict";  
  
    const navbar= document.querySelector("#main-nav");
  
    document.addEventListener("scroll", (e) => {
      const scrolled = document.scrollingElement.scrollTop;
     
      if (scrolled > 80) { //adjust to suit your need of when transition start
        navbar.classList.add("scrolled");
      } else {
        navbar.classList.remove("scrolled");
      }
    });
  })(); 

Step three: create a new css file and add the following:

#main-nav {
  background: transparent;
  transition: background  250ms ease-in; /*duration of fade transition */
}

#main-nav.scrolled {
  background: white;
}
1 Like

Thanks for the answer, but I tried it and it didn’t work for me unfortunately.

You must have missed something :slight_smile:

I have made you an example bss file which you can download here.
https://dropover.cloud/af0cc1

I changed the colors to red and blue so you can see what is happening, these can easily be changed in the css

1 Like