Agent Zebra
Agent Zebra

Reputation: 4550

close bootstrap collapse menu when clicking on navbar-brand

I'm trying to get the collapsed navbar - when open - to close when the navbar-brand title is clicked. At the moment if the bootstrap collapsed navbar is open and the navbar-brand (which in this case says 'fried onions') is clicked, the navbar does not close. It closes in all other instances.

I think I just need to add a to '.navbar-collapse.in' so it's really just a syntax issue. I tried '.navbar-collapse.in' && 'a' and also '.navbar-collapse.in || a' neither worked.

Here's a plunker

And here's the relevant JS.

   $(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle' ) {
        $(this).collapse('hide');
    }
});


  $(document).ready(function () {

    $(function () {
     /*   $('li a').click(function (e) { */
        $('a').click(function (e) {
            $('a').removeClass('active');
            $(this).addClass('active');
        });
    });
});

Upvotes: 2

Views: 1946

Answers (1)

kittenchief
kittenchief

Reputation: 1255

Bootstrap actually opens and closes the navbar using the HTML5 data-* attributes data-toggle and data-target. These are generally added to the "close" button of the navbar like data-toggle="collapse" and data-target="#navbar". But you can add them anywhere and they'll work.

I have tried this and it seems to work:

<a class="navbar-brand" data-toggle="collapse" data-target="#navbar" ui-sref="home">Fried <span class="navbar-brand-bold">Onions</span></a>

It's just adding the data-toggle="collapse" and data-target="#navbar" to the .navbar-brand ("Fried Onions").

Edit:

If the above solution doesn't work, then remove the data-toggle and data-target from .navbar-brand and add some jQuery instead:

$(function(){
  $(".navbar-brand").click(function(){
    if ($(".collapse.in")) {
      $(".collapse.in").animate({height: '1px'}, 500, function(){
        $(".collapse.in").removeClass("in");
      });
    }
  });
});

Upvotes: 3

Related Questions