2

I require to create a sliding menu from the left. I have successfully create this however to close the menu we need to again touch / click the navigation icon. I need the menu to slide in when someone touches outside the menu area.

Link to what I have done so far. http://rpinvestments.co.in/app/

Following is my JS code:

/*Main Navigation*/
$(function() {
    var html = $('html, body'),
        navContainer = $('.nav-container'),
        navToggle = $('.nav-toggle'),
        navDropdownToggle = $('.has-dropdown');

    navToggle.on('click', function(e) {
        var $this = $(this);
        e.preventDefault();
        $this.toggleClass('is-active');
        navContainer.toggleClass('is-visible');
        html.toggleClass('nav-open');
    });

    navDropdownToggle.on('click', '*', function(e) {
        e.stopPropagation();
    });


});
Utpal - Ur Best Pal
  • 4,472
  • 3
  • 17
  • 28
  • http://stackoverflow.com/questions/25089297/twitter-bootstrap-avoid-dropdown-menu-close-on-click-inside refer this – pratikpawar Feb 06 '16 at 04:00

2 Answers2

1

Try this:

jsFiddle Demo

var html = $('html, body'),
    navContainer = $('.nav-container'),
    navToggle = $('.nav-toggle'),
    navDropdownToggle = $('.has-dropdown');

navToggle.on('click', function(e) {
  var $this = $(this);
  e.preventDefault();
  e.stopPropagation(); //<-- Added This
  $this.toggleClass('is-active');
  navContainer.toggleClass('is-visible');
  html.toggleClass('nav-open');
});

navDropdownToggle.on('click', '*', function(e) {
  e.stopPropagation();
});

$('body').click(function(){ //<--- Added this section
    navToggle.toggleClass('is-active');
    navContainer.toggleClass('is-visible');
    html.toggleClass('nav-open');
});
cssyphus
  • 37,875
  • 18
  • 96
  • 111
1

I appreciate this is old and marked as solved, but I just stumbled across this when looking into click to close events. The above answer is great, however it also opens the menu on body clicks, which kind of defeats the point of the fancy hamburger button. Here is a simple addition to the above code which solves this issue.

$(document).ready(function() {
var html = $('html, body'),
navContainer = $('.nav-container'),
navToggle = $('.nav-toggle'),
navDropdownToggle = $('.has-dropdown');

navToggle.on('click', function(e) {
var $this = $(this);
e.preventDefault();
e.stopPropagation();
$this.toggleClass('is-active');
navContainer.toggleClass('is-visible');
html.toggleClass('nav-open');
});

navDropdownToggle.on('click', '*', function(e) {
e.stopPropagation();
});

$('body').click(function(){
if (html.hasClass("nav-open")) { // -- added this line --
navToggle.toggleClass('is-active');
navContainer.toggleClass('is-visible');
html.toggleClass('nav-open');
} 
});
});

I also added the $(document).ready (function() { to the beginning so anyone else in the future can just copy, paste and go with a few class name changes.