Alex Zahir Alex Zahir - 4 months ago 35
CSS Question

jQuery hide bootstrap slide menu when clicked anywhere on the screen

Made a Fiddle here:

https://jsfiddle.net/r94dq2e4/

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
$('#bs-example-navbar-collapse-2')
.on('show.bs.collapse', function (e) {
$('body').addClass('menu-slider');
})
.on('shown.bs.collapse', function (e) {
$('body').addClass('in');
})
.on('hide.bs.collapse', function (e) {
$('body').removeClass('menu-slider');
})
.on('hidden.bs.collapse', function (e) {
$('body').removeClass('in');
});

})(jQuery);


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



Menu



<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>

</ul>
</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 */
$(document).click(function(e){

// Check if click was triggered on or within #menu_content
if( $(e.target).closest("#navbar2").length > 0 ) {
return false;
}
// Otherwise
// trigger your click function
$('body').removeClass('menu-slider');
$('body').removeClass('in');

});


Thank you

Answer

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 (!$(e.target).hasClass('navbar-collapse') && !$(e.target).hasClass('nav') && $(e.target).parents('.nav').length == 0) {
    $('#bs-example-navbar-collapse-2').removeClass('in');
}

You can try it in this fiddle: https://jsfiddle.net/r94dq2e4/1/