Changing nav-bar color after scrolling?

Solution 1:

Here is simplest way how to change navbar color after window scroll:

Add follow JS to head:

$(function () {
  $(document).scroll(function () {
    var $nav = $(".navbar-fixed-top");
    $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
  });
});

and this CSS code

.navbar-fixed-top.scrolled {
  background-color: #fff !important;
  transition: background-color 200ms linear;
}

Background color of fixed navbar will be change to white when scroll exceeds height of navbar.

See follow JsFiddle

Solution 2:

Here is a jsfiddle example. Using Jquery to change the background color based on scroll pixel position.

Here is a fiddle using bootstrap

$(document).ready(function(){       
   var scroll_start = 0;
   var startchange = $('#startchange');
   var offset = startchange.offset();
    if (startchange.length){
   $(document).scroll(function() { 
      scroll_start = $(this).scrollTop();
      if(scroll_start > offset.top) {
          $(".navbar-default").css('background-color', '#f0f0f0');
       } else {
          $('.navbar-default').css('background-color', 'transparent');
       }
   });
    }
});

Solution 3:

this is a simple pure javascript

var myNav = document.getElementById('mynav');
window.onscroll = function () { 
    "use strict";
    if (document.body.scrollTop >= 200 ) {
        myNav.classList.add("nav-colored");
        myNav.classList.remove("nav-transparent");
    } 
    else {
        myNav.classList.add("nav-transparent");
        myNav.classList.remove("nav-colored");
    }
};

in some chrome versions there is bug with:

document.body.scrollTop

so you may add a condition like this:

 if (document.body.scrollTop >= 200 || document.documentElement.scrollTop >= 200 )

sure you must have 2 classes

.nav-colored { background-color:#000; }
.nav-transparent { background-color:transparent;}

Solution 4:

i think this solution is shorter and simpler than older answers. This is Js Code:

const navbar = document.querySelector('.nav-fixed');
window.onscroll = () => {
    if (window.scrollY > 300) {
        navbar.classList.add('nav-active');
    } else {
        navbar.classList.remove('nav-active');
    }
};

And my css:

header.nav-fixed {
    width: 100%;
    position: fixed;
    transition: 0.3s ease-in-out;
}

.nav-active {
    background-color:#fff;
    box-shadow: 5px -1px 12px -5px grey;
}