DEV Community

sid
sid

Posted on

1 1

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more