Alex Zahir Alex Zahir - 5 months ago 40
CSS Question

jQuery hide bootstrap slide menu when clicked anywhere on the screen

Made a Fiddle here:

I am using twitter bootstap version 3 with a slide in menu from the left when navbar toggle button is clicked.

This is the jQuery code I'm using:

// Nav
(function ($) {
'use strict';

// Toggle classes in body for syncing sliding animation with other elements
.on('', function (e) {
.on('', function (e) {
.on('', function (e) {
.on('', function (e) {


This works well and on first click of the navbar toggle button, the menu slides in, when clicked again, the menu slides out. I would like to enhance this functionality in such a way that the menu slides out when the user clicks anywhere on the page except for the menu itself.

This is my HTML for the menu:

Toggle navigation


<div class="navbar-collapse collapse" id="bs-example-navbar-collapse-2">
<ul class="nav navbar-nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Treatments<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Menu Item</span></a></li>

<li><a href="#">About Us</a></li>
<li><a href="#">Meet the team</a></li>
<li><a href="#">See the results</a></li>
<li><a href="#">Cost</a></li>
<li><a href="#">Information</a></li>
</ul><!-- end navbar-nav -->
</div><!-- end navbar-collapse -->
</nav><!-- end navbar -->

I have started with the following jQuery code to achieve this. But I would need some help in where to go from here:

/* Nav click outside hide navbar */

// Check if click was triggered on or within #menu_content
if( $("#navbar2").length > 0 ) {
return false;
// Otherwise
// trigger your click function


Thank you


There are 3 things that you need to check in order to see if you should close the menu:

  1. The element is not the nav itself (.nav)
  2. The element is not the nav container (.navbar-cllapse)
  3. The element is not a child-element of the nav (.parents('.nav'))

if (!$('navbar-collapse') && !$('nav') && $('.nav').length == 0) {

You can try it in this fiddle: