Changing a html navbar on scroll + Tailwindcss integration

sidcraftscode

sid

Posted on December 27, 2020

Changing a html navbar on scroll + Tailwindcss integration

I just came across this simple trick to change a navbar on scroll using pure javascript.

 window.onscroll = () => {
  const nav = document.querySelector('#navbar');
  if(this.scrollY <= 10) nav.className = 'normal'; else nav.className = 'scrolled';
};
Enter fullscreen mode Exit fullscreen mode

Keep in mind that you have to add all the classes you already have if you want to maintain a look.

Tailwindcss

This can be especially useful if you are using Tailwindcss
This is because you can add classes prebuilt from tailwindcss, such as shadow, shadow-2xl, and bg-black. You can check out an example of this on my site. Notice how the navbar gets a shadow when scrolled.

Thanks for reading. If you liked the article, you can buy me a coffee!

💖 💪 🙅 🚩
sidcraftscode
sid

Posted on December 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related