💻 Programming

Create a fixed transparent navbar on scroll with tailwind and minimal js

Bolu Abiola

21st Mar 2024

Create a fixed transparent navbar on scroll with tailwind and minimal js

To achieve our transparent effect, we'll need to use the transparent CSS property which can work either of two ways:

  1. Nav with a background color and opacity set to a certain value

  2. Nav with a background color set with rgba, with the "a" set for opacity.

But, we'll go with option 1...

<nav class="flex justify-between bg-gray-900 opacity-90 text-white py-6 px-10 fixed top-0 right-0 left-0 h-20">
  <span>LOGO</span>
  <ul class="flex gap-6">
    <li>
      <a href="#">Home</a>
    </li>
    <li>
      <a href="#">About</a>
    </li>
    <li>
      <a href="#">Projects</a>
    </li>
    <li>
      <a href="#">Contact</a>
    </li>
  </ul>
</nav>

Here we set our background color to bg-gray-900 and we have a fixed opacity of 90 i.e. opacity-90 (which in tailwind lingo translates to 0.9). This looks good so far, but we want our opacity to only show when we scroll. To do that we need to:

  • Remove opacity-90 from the navbar (so we can dynamically toggle with js) and add an id to our navbar.

    <nav id="navbar" class="...">
      <!-- Your content here -->
    </nav>

  • Utilize the window.scrollY property (available from the web APIs) to toggle the 'opacity-90' className. This should be in a new file called index.js or whatever floats your boat

    window.addEventListener('scroll', function() {
      const navbar = document.getElementById('navbar');
      const hasScrolled = window.scrollY > 50;
    
      if(hasScrolled) {
        navbar?.classList.add('opacity-90')
      } else {
        navbar?.classList.remove('opacity-90')
      }
    });

Everything all together should look a bit like this:

<nav id="navbar" class="...">
  <span>LOGO</span>
  <ul class="flex gap-6">
    <li>
      <a href="">Home</a>
    </li>
    <li>
      <a href="">About</a>
    </li>
    <li>
      <a href="">Projects</a>
    </li>
    <li>
      <a href="">Contact</a>
    </li>
  </ul>
</nav>

window.addEventListener('scroll', function() {
  const navbar = document.getElementById('navbar');
  const hasScrolled = window.scrollY > 50;

  if(hasScrolled) {
    navbar?.classList.add('opacity-90')
  } else {
    navbar?.classList.remove('opacity-90')
  }
});

A quick breakdown of our JS snippet:

  • Whenever we scroll down on our application page, a value exists which shows the position we are on our page starting from 0 to how long the website page is.

  • We check that number to confirm if it has increased by a certain value (50), if it has, it means the page has been scrolled down and we can add transparency to our navbar

  • If the number is less than our expected value, then we're still at the top and should remove opacity.

Alright, have a nice day, Bye.

🤝 Share