OWENNNN OWENNNN - 1 year ago 85
CSS Question

How to change navbar-default to navbar-inverse on scroll?

At the top of my website, the main navigation class is:

navbar navbar-default navbar-fixed-top bg

I am trying to make it so when you scroll, the class changes to so I can create a more elegant and easier scroll animation:

navbar navbar-inverse navbar-fixed-top bg

How is this accomplished with Javascript? I can't find ANYTHING on the internet...the one thing I did find let you remove one class but doesn't work because I have like 10 different classes at once...

Answer Source

Here's an example.

Use $(window).scroll() and addClass() to add the bg class to your nav when you scroll down past a certain point. Note that addClass and removeClass allow you to add/remove individual class names from tags where multiple classes exist.

Note that you will probably need to use !important to force the color change -- bootstrap can be tenacious.

var viz=true, win = $(window), nav=$('nav');


    pos = win.scrollTop();
    if ( viz && pos > 100 ){
      viz = false;
    }else if ( !viz && pos < 100 ){
      viz = true;

html {
  height: 2000px;
.bg{background:green !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span> 
      <a class="navbar-brand" href="#">WebSiteName</a>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a>
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1
        <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Page 1-1</a>
            <li><a href="#">Page 1-2</a>
            <li><a href="#">Page 1-3</a>
        <li><a href="#">Page 2</a>
        <li><a href="#">Page 3</a>