Here is a Fiddle link:
https://jsfiddle.net/r94dq2e4/
I have incorporated a slide-in menu from the left in my website using Twitter Bootstrap version 3. The menu appears when the navbar toggle button is clicked.
This is the jQuery code responsible for the sliding animation:
// Nav
(function ($) {
'use strict';
// Toggle classes in body to sync 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);
The current functionality works well, where the menu slides in on the first click of the navbar toggle button and slides out on the second click. However, I aim to improve this behavior so that clicking anywhere on the page outside of the menu area will hide the menu.
Below is the HTML structure of 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 to implement additional jQuery code to achieve this functionality. However, I am seeking guidance on how to proceed:
/* 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');
});
Your assistance is greatly appreciated.