Help with fixed menu with logo swop

Built my first BSS site and all went great. Just have one issue that probably is advanced.
I have a fixed navbar that is dark until you scroll down, then it changes to light.
Problem is: I have a light logo for the dark navbar and a dark logo for the light navbar and I don’t know how to set it up so that it changes depending on scroll.

You can see example here: https://pps.novagiantdemo.com/
If anyone can help - thank you!

Set your light logo img to have class of lightLogo, and the dark logo to have class of darkLogo

You will also need your logos in the link

<a href="#page-top">
<img class="lightLogo" src="assets/img/logo-600-white.webp" width="213" height="83">
<img class="darkLogo"src="assets/img/logo-600.webp" width="213" height="83">
</a>

Also “href=”#page-top" shouldn’t be in the img tag, as you currently have

then add something along the lines of the following scss:

#mainNav.navbar-shrink {
  .darkLogo {
    display: none;
  }

  .lightLogo {
    display: block;
  }
}

#mainNav:not(.navbar-shrink) {
  .darkLogo {
    display: block;
  }

  .lightLogo {
    display: none;
  }
}
    

or css:

#mainNav.navbar-shrink .darkLogo {
  display: none;
}
#mainNav.navbar-shrink .lightLogo {
  display: block;
}

#mainNav:not(.navbar-shrink) .darkLogo {
  display: block;
}
#mainNav:not(.navbar-shrink) .lightLogo {
  display: none;
}

This will use your existing javascript

1 Like

This is really more of a Webdesign Help category question, but basically you need to use JavaScript to add/remove a class on scroll.

I’m an amateur with JS, and it’s entirely possible there’s a better way than this (someone else my chime in), but here’s one way to do it…

Make the logo the background image of a div. Give the div a class of .logo. Then create two CSS classes, one called .logo that has the light logo as the background image, and the other called .logo-dark that has the dark logo as the background image.

Then create a new JS file with the following code in it…

document.addEventListener('DOMContentLoaded', () => {
  const logo = document.querySelector('.logo');
  
  window.addEventListener('scroll', () => {
    const scroll = window.scrollY;

    if (scroll >= 120) {
      logo.classList.remove('logo');
      logo.classList.add('logo-dark');
    } else {
      logo.classList.remove('logo-dark');
      logo.classList.add('logo');
    }
  });
});

When the user scrolls past 120 pixels, the class with the light logo is removed, and the class with the dark logo is added. When they scroll back up, the opposite happens. You might need to change the number depending on your when your header changes color.

1 Like

Thank you! That worked beautifully and easily!

1 Like