Home Web Development Bootstrap Solution to: How do I make Bootstrap 3 collapsable menus retract or...

Get social!


For a project using Bootstrap version 3 and focusing on mobile devices, I had the following Bootstrap navigation menu on one of my pages:

  <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          <a class="navbar-brand" href="#">Prudential Fox &amp; Roach</a>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#"><div class="menu-icon-spacer icon-home">&nbsp;&nbsp;</div>Property List</a></li>
            <li><a href="#"><div class="menu-icon-spacer icon-map-marker">&nbsp;&nbsp;</div>Map View</a></li>
            <li><a href="#" rel="filter"><div class="menu-icon-spacer icon-search">&nbsp;&nbsp;</div>Filter Properties List</a></li>
        </div><!--/.nav-collapse -->

Pretty standard stuff. When viewed on an iPhone or Android phone, the menu looks something like the photo below.


When someone clicks on a menu link (for instance, the "Filter Properties List" link), a modal dialog comes up (not a Bootstrap dialog -- my own homegrown version). It slides in from the bottom. After the user is done with it, they can click the "Done" button and it slides back out again. The problem is that the Bootstrap menu is still open. To me, it would be nicer if the menu closed after you clicked an item on it. It does this in some circumstances, but not all.


After mucking around with css transitions and various jQuery calls, I finally settled on the following code:

   $(function() {
        // Close bootstrap's dropdown menu after clicking
        $('div.collapse ul.nav li a').each(function() {
            $(this).on("click", function () {
                var $obj = $($(this).parents('.in')[0]);
                $obj.animate({'height': '1px'}, function() {

With it, when a user clicks on a menu item, the menu retracts immediately afterwards. There's probably a cleaner way to do this (I wonder if Bootstrap already has this functionality built in?) and jQuery can grow teeth when used like a sledgehammer. Still, it seems to be working OK so far. So file this solution under "whatever works".

Bad Behavior has blocked 78 access attempts in the last 7 days.