Search code examples
jquerytwitter-bootstrapnavbar

bootstrap collapsing navbar shows extra animation when collapse with js


When using bootstraps default navbar: http://getbootstrap.com/components/#navbar, the menu will not collapse automatically, when selecting a menu item.

I want to change this behaviour with the following code:

$(document).ready(function(){

    var activatableButtons = $('.nav.navbar-nav a'),
        navbar = $('#bs-example-navbar-collapse-1');

    activatableButtons.click(function(){
        navbar.collapse('hide');
    });

});

I am using:

  1. jquery 2.1.0
  2. bootstrap 3.2.0
  3. HTML: Default Navbar example http://getbootstrap.com/components/#navbar

I set up a jsfiddle: http://jsfiddle.net/Ludmilla/5c3supgt/

PROBLEM DESCRIPTION: animations seen when selecting a menu button.

seemingly the collapse state of the menu is toggled, when clicking the first and second time. After the two initial clicks everything works as expected - no more animations.

Q: how to set things up, so that the state after 2 clicks is present right at the start?

TEST 1:

  • make browser wide, so that menu is in 'desktop mode'
  • Run code
  • click on one of the 'Link' buttons -> ERROR: some animation is seen
  • click on one of the 'Link' buttons -> ERROR: some animation is seen
  • click on one of the 'Link' buttons -> OK: no animation

no more animations - OK

TEST 2:

  • make browser wide, so that menu is in 'desktop mode'
  • Run code
  • click on one of the 'Link' buttons -> ERROR: some animation is seen
  • make browser narrow, so that menu is in 'phone mode' -> ERROR: menu is open

Solution

  • The solution was simple: just one extra line needed, to get things initialized properly:

    $(document).ready(function(){
    
        var activatableButtons = $('.nav.navbar-nav a'),
            navbar = $('#bs-example-navbar-collapse-1');
    
        // this extra line fixes the problem:
        navbar.collapse({toggle: false});
    
        activatableButtons.click(function(){
            navbar.collapse('hide');
        });
    
    });