Change navbar style with scroll

Asked

Viewed 1,378 times

2

I’ve been looking for a way to make a navbar bootstrap 3 has a behavior similar to Google+ navbar, when scrolling down it gets smaller and displays in place of menus with icon and title only menus with icon, when returning to the top it takes the initial style.

For example, by default my navbar has 47px, when giving scroll she would be with some 30px.

Code of my navbar 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>
  • maybe this pen will help you, http://codepen.io/haykou/pen/FHKJg

1 answer

2

You can make a javascript for the scroll event.

See this example, which puts the fixed navbar 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
      }
  });
});
  • In this example the navbar has id="navbar".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.