Explain Codes LogoExplain Codes Logo

Changing nav-bar color after scrolling?

html
responsive-design
css-transitions
performance
Anton ShumikhinbyAnton ShumikhinΒ·Oct 12, 2024
⚑TLDR

You can alter your nav-bar's color based on the scroll position by listening to the scroll event window.onscroll. Make sure you compare the current scrollY (using window.scrollY or window.pageYOffset) against your desired scroll limit and switch the class of your nav-bar to manifest the new color using CSS.

See the bite-sized example below:

// Adding style on scroll (and humor 😜) one pixel at a time window.addEventListener('scroll', () => { document.querySelector('.navbar').classList.toggle('scrolled', window.scrollY > 50); });

And the complementary CSS:

.navbar { transition: background-color 0.3s; /* Smooth operator */ } .navbar.scrolled { background-color: #333; /* Dark side of the scroll */ }

Feel free to adjust the 50 in window.scrollY > 50 to calibrate the scroll threshold to your taste.

Opt for smoothness with CSS transitions

Ensure smooth sailing with CSS transitions

To enjoy a smooth transition between colors, CSS transitions can be implemented - every designer's tiny secret for professional-looking effects!

Use classes to manage your state

In managing your styles better, you can use multiple CSS classes for various nav-bar states. This keeps the JavaScript light and the styles adaptable!

.navbar { transition: background-color 0.3s; /* Smooth as butter! */ } .navbar.top-of-page { background-color: #fff; /* Pure as snow */ } .navbar.scrolled { background-color: #333; /* Dark knight rises */ }

You can now toggle between .top-of-page and .scrolled based on the scroll position.

Improving scroll performance with JavaScript

Use IntersectionObserver for improved speed

It gets better with the IntersectionObserver API, a modern approach to detect when elements appear in view. Instead of the outdated scroll event, chirp to the IntersectionObserver when you want the navbar color to switch as the page sections flow by.

let observer = new IntersectionObserver((entries) => { entries.forEach(entry => { document.querySelector('.navbar').classList.toggle('scrolled', !entry.isIntersecting); }); }, { rootMargin: '-50px 0px' }); // Now, observe "the watcher on the wall" πŸ˜„ observer.observe(document.querySelector('#triggerElement'));

Scrolling just got efficient with Debouncing

Debouncing or throttling your scroll event handlers can ramp up performance, especially for low-power devices because not all scrolls have to make headlines!

let lastScrollPosition = 0; let ticking = false; window.addEventListener('scroll', () => { lastScrollPosition = window.scrollY; if (!ticking) { window.requestAnimationFrame(() => { // Where the magic happens! document.querySelector('.navbar').classList.toggle('scrolled', lastScrollPosition > 50); ticking = false; }); ticking = true; } });

Taking your nav-bar to the next level

Make it sticky

If you're keen on keeping your navbar visibly consistent while scrolling, remember to set the position CSS property to fixed or sticky.

.navbar { position: sticky; top: 0; /* Stick with me, will ya */ }

Top of the page? No problem!

It's good practice to set a default color for the nav-bar at the top of the page. It provides a gentle visual hint that no scrolling has taken place yet.

.navbar { background-color: #fff; /* I love the purity of... white! */ }

jQuery for the effervescent coder

If you're a jQuery fan, feel free to use its native scroll events:

$(window).scroll(function() { $('.navbar').toggleClass('scrolled', $(this).scrollTop() > 50); });

Cross-browser scrollTop for the savvy developer

Be wary of scrollTop variation across browsers. Use document.documentElement.scrollTop or document.body.scrollTop to cater to all different tastes:

let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

Living on the gradient

One more thing - start off with an eleborate linear-gradient background for your navbar for that extra touch of sophistication before the scrolling fiesta begins!

.navbar { background: linear-gradient(to right, #ffafbd, #ffc3a0); /* Let's gradient-party! */ }