Ecommerce Shopify WordPress Discussion

Making nav (.navbar) change background colour on scroll down isnt working

I am struggling to make the nav class .navbar change background-color on scroll down. I've used this code and some others, it's not working no matter what I try to implement. I am trying to get the nav to add the alt-color class after the view has left the top of the page jQuery(document).ready(function($) { $(window).scroll(function() { var scrollPos = $(window).scrollTop(), navbar = $('.navbar'); if (scrollPos > 10) { navbar.addClass('alt-color'); } else { navbar.removeClass('alt-color'); } }); }); .navbar { transition: 0.2s all linear; background-color: #212121; height: 100px; width: 100%; } .navbar.alt-color { background-color: #fff !important; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav class="navbar"> </nav> Run code snippetExpand snippet
As already said, you do not need to use jQuery. JQuery becomes more and more outdated and vanilla JS can do this as easy. Simply add an Event Listener to the window: window.addEventListener and check for the scroll event. Then you can add the class there based on a condition with classList.toggle. Toggle allows for a second parameter as condition. In this case: this.scrollY > 10 window.addEventListener('scroll', function() { const NAVBAR = document.querySelector('nav'); NAVBAR.classList.toggle('alt-color', this.scrollY > 10); }) .navbar { transition: 0.2s all linear; background-color: #212121; height: 100px; width: 100%; } .navbar.alt-color { background-color: blue; } /* added for demo purpose */ body { min-height: 800vh; } nav { position: sticky; top: 0; } <nav class="navbar"></nav> Run code snippetExpand snippet

January 10, 2024

TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.