[javascript] Bootstrap close responsive menu "on click"

On "PRODUCTS" click I slide up a white div (as seen in attached). When in responsive (mobile and tablet), I would like to automaticly close the responsive navbar and only show the white bar.

I tried:

$('.btn-navbar').click();  

also tried:

$('.nav-collapse').toggle();

And it does work. However in desktop size, it is also called and does something funky to the menu where it shrinks for a second.

Any ideas?

enter image description here

This question is related to javascript html css twitter-bootstrap

The answer is


I'm using the mollwe function, although I added 2 improvements:

a) Avoid the dropdown closing if the link clicked is collapsed (including other links)

b) Hide the dropdown too, if you are clicking the visible web content.

jQuery.fn.exists = function() {
                  return this.length > 0;
              }

    $(function() {
                var navMain = $(".navbar-collapse");
                navMain.on("click", "a", null, function() {
                    if ($(this).attr("href") !== "#") {
                        navMain.collapse('hide');
                    }
                });

                $("#content").bind("click", function() {
                     if ($(".navbar-collapse.navbar-ex1-collapse.in").exists()) {
                        navMain.collapse('hide');
                    }
                });

            });

I really liked Jake Taylor's idea of doing it without additional JavaScript and taking advantage of Bootstrap's collapse toggle. I found you can fix the "flickering" issue present when the menu isn't in collapsed mode by modifying the data-target selector slightly to include the in class. So it looks like this:

<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse.in">Products</a></li>

I didn't test it with nested dropdowns/menus, so YMMV.


I'm assuming you have a line like this defining the nav area, based on Bootstrap examples and all

<div class="nav-collapse collapse" >

Simply add the properties as such, like on the MENU button

<div class="nav-collapse collapse" data-toggle="collapse"  data-target=".nav-collapse">

I've added to <body> as well, worked. Can't say I've profiled it or anything, but seems a treat to me...until you click on a random spot of the UI to open the menu, so not so good that.

DK


if menu html is

<div id="nav-main" class="nav-collapse collapse">
     <ul class="nav">
         <li>
             <a href='#somewhere'>Somewhere</a>
         </li>
     </ul>
</div>

on nav toggle 'in' class is added and removed from the toggle. check if responsive menu is opened then perform the close toggle.

$('.nav-collapse .nav a').on('click', function(){
    if ( $( '.nav-collapse' ).hasClass('in') ) {
        $('.navbar-toggle').click();
    }
});

You cau use

ul.nav {
    display: none;
}

This will by default close the navbar. Please let me know anybody finds this usefull


Bootstrap 4 solution without any Javascript

Add attributes data-toggle="collapse" data-target="#navbarSupportedContent.show" to the div <div class="collapse navbar-collapse">

Make sure you provide the correct id in data-target

<div className="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">

.show is to avoid menu flickering in large resolutions

_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown_x000D_
        </a>_x000D_
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <div class="dropdown-divider"></div>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link disabled" href="#">Disabled</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_


Not the newest thread but i searched for a solution for the same Problem and found one (a mix of some others).

I gave the NavButton:

<type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> ...

an id / Identifier like:

 <button id="navcop" type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

Not the finest "Idea" - but: Works for me! Now you can check up the visibility of your button (with jquery) like:

 var target = $('#navcop');
   if(target.is(":visible")){
   $('#navcop').click();
   }

(NOTE: This is just a Code snipped ! I used a "onclick" Event on my Nav Links! (Starting a AJAX Reguest.)

The result is: If the Button is "visible" it got "clicked" ... So: No Bug if you use the "Fullscreen view" of Bootstrap (width of over 940px).

Greetings Ralph

PS: It works fine with IE9, IE10 and Firefox 25. Didnt checked up others - But i can't see a Problem :-)


this solution have a fine work, on desktop and mobile.

<div id="navbar" class="navbar-collapse collapse" data-toggle="collapse"  data-target=".navbar-collapse collapse">

You don't have to add any extra javascript to what's already included with bootstraps collapse option. Instead simply include data-toggle and data-target selectors on your menu list items just as you do with your navbar-toggle button. So for your Products menu item it would look like this

<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>

Then you would need to repeat the data-toggle and data-target selectors for each menu item

EDIT!!! In order to fix overflow issues and flickering on this fix I'm adding some more code that will fix this and still not have any extra javascript. Here is the new code:

<li><a href="#products" class="hidden-xs">Products</a></li>
<li><a href="#products" class="visible-xs" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>

Here it is at work http://jsfiddle.net/jaketaylor/84mqazgq/

This will make your toggle and target selectors specific to screen size and eliminate glitches on the larger menu. If anyone is still having issues with glitches please let me know and I'll find a fix. Thanks

EDIT: In the bootstrap v4.1.3 I couldnt use visible/hidden classes. Instead of hidden-xs use d-none d-sm-block and instead of visible-xs use d-block d-sm-none.


This should do the trick.

Requires bootstrap.js.

Example => http://getbootstrap.com/javascript/#collapse

    $('.nav li a').click(function() {
      $('#nav-main').collapse('hide');
    });

This does the same thing as adding 'data-toggle="collapse"' and 'href="yournavigationID"' attributes to navigation menus tags.


This works, but does not animate.

$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');

$('.navbar-toggle').trigger('click');

I think you are all over engineering..

    $('.navbar-collapse ul li a').click(function(){ 
            $('.navbar-toggle:visible').click();
    });

EDIT: To take care of sub menus, make sure their toggle anchor has the dropdown-toggle class on it.

    $(function () { 
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function () { 
                    $('.navbar-toggle:visible').click(); 
            }); 
    });

EDIT 2: Add support for phone touch.

    $(function () {
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').bind('click touchstart', function () {
                    $('.navbar-toggle:visible').click();
            });
    });

Just to spell out user1040259's solution, add this code to your $(document).ready(function() {});

    $('.nav').click( function() {
        $('.btn-navbar').addClass('collapsed');
        $('.nav-collapse').removeClass('in').css('height', '0');
    });

As they mention, this doesn't animate the move... but it does close the nav bar on item selection


Tuggle Nav Close, IE browser compatible answer, without any console error. If you are using bootstrap, use this

$('.nav li a').on('click', function () {
    if ($("#navbar").hasClass("in")) {
        $('.navbar-collapse.in').show();
    }
    else {
        $('.navbar-collapse.in').hide();
    }
})

If for example your toggle-able icon is visible only for extra small devices, then you could do something like this:

$('[data-toggle="offcanvas"]').click(function () {
    $('#side-menu').toggleClass('hidden-xs');
});

Clicking [data-toggle="offcanvas"] will add bootstrap's .hidden-xs to my #side-menu which will hide the side-menu content, but will become visible again if you increase the window size.


For those using AngularJS and Angular UI Router with this, here is my solution (using mollwe's toggle). Where ".navbar-main-collapse" is my "data-target".

Create directive:

module.directive('navbarMainCollapse', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'C',
        link: function (scope, element) {
            //watch for state/route change (Angular UI Router specific)
            $rootScope.$on('$stateChangeSuccess', function () {
                if (!element.hasClass('collapse')) {
                    element.collapse('hide');
                }
            });
        }
    };
}]);

Use Directive:

<div class="collapse navbar-collapse navbar-main-collapse">
    <your menu>

just to be complete, in Bootstrap 4.0.0-beta using .show worked for me...

<li>
  <a href="#Products" data-toggle="collapse" data-target=".navbar-collapse.show">Products</a>
</li>

In the HTML I added a class of nav-link to the a tag of each navigation link.

$('.nav-link').click(
    function () {
        $('.navbar-collapse').removeClass('in');
    }
);

This worked for me. I have done like, when i click on the menu button, im adding or removing the class 'in' because by adding or removing that class the toggle is working by default. 'e.stopPropagation()' is to stop the default animation by bootstrap(i guess) you can also use the 'toggleClass' in place of add or remove class.

$('#ChangeToggle').on('click', function (e) {

        if ($('.navbar-collapse').hasClass('in')) {
            $('.navbar-collapse').removeClass('in');
            e.stopPropagation();
        } else {
            $('.navbar-collapse').addClass('in');
            $('.navbar-collapse').collapse();
        }

    });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation