Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading