Change navbar style with scroll

2

I've been looking for a way to make a navbar bootstrap 3 have a behavior similar to Google+ navbar, while scrolling down it gets smaller and displays instead of menus with icon and title only menus with icon, when returning to the top it assumes the initial style.

For example, by default my navbar has 47px , when scrolling it would look like 30px .

Navbar code for example:

<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active">
                    <a href="#"><i class="fa fa-home"></i> Home</a>
                </li>
                <li>
                    <a href="#about"><i class="fa fa-question"></i> About</a>
                </li>
            </ul>
        </div>
    </div>
</nav>
    
asked by anonymous 29.01.2015 / 16:44

1 answer

2

You can do a javascript for the scroll event.

See this example, which places the navbar fixed at the top only when the scroll scrolls to the top of the navbar:

$(function(){ //
   var navbarTop = $('#navbar').offset().top; // retorna a posicao

   $(window).scroll(function(){ // evento scroll
      var windowTop = $(window).scrollTop();

      if (navbarTop < windowTop) {
          $('#navbar').addClass("navbar-fixed-top"); //adiciona a classe
          //$('#navbar').css({ position: 'fixed', top: 0 }); ou altere o estilo conforme quiser
      } else {
          $('#navbar').removeClass("navbar-fixed-top"); //remove a classe
          //$('#navbar').css('position','static'); ou altere o estilo
      }
  });
});
    
30.01.2015 / 18:30