1

I'm sorry if i've asked the same question, but i've tried any solution but still got nothing for me.. As like the title, i want to close mobile menu when i click at outside of the area menu. Here is my jquery when using toggler button

$('.mobile-nav-toggler').click(function() {
    $('.mobile-nav-overlay').fadeToggle(200)
    $('.mobile-nav-toggler').toggleClass('active')
    $('body').toggleClass('mobile-nav-opened')
  });

mobile-nav-overlay is the layer menu. Anyone can help me? Thanks

jack asad
  • 13
  • 3

3 Answers3

0

After mobile menu will be clicked, and it will be opening, add under this menu div with 100% width and height and opacity will be what you need. After this add another script, and it will be saying: close menu when clicked .div-under-menu

$('.new-div-under-menu').click(function() {
     $('.menu').hide() // or removeClass, or toggle or something
     $('.new-div-under-menu').hide()
});
LiH
  • 382
  • 3
  • 7
  • 21
0

Something as simple as this should work: Basically, on any click on the page(html click) it checks if the body has the class 'mobile-nav-opened' which exists only when menu is opened, so if this is the case you can hide your menu here.

This event is not taking place as long as you click on the nav container('.mobile-nav' in my example).

$('html').click(function() {
    if ($('body').hasClass('mobile-nav-opened')){
        // Hide your menu here
    }
});

// replace mobile-nav with your entire nav container
$('.mobile-nav').click(function(e){
    e.stopPropagation();
});
Cata John
  • 1,371
  • 11
  • 19
0

One can do it using the following code:

Note: The 'Mobile Nav Toggle' text with the Red background shows mobile-menu is Off; with Green background, it is On.

return false is important in the toggler method > mobileMenuToggle in this case.

$(function() {
  mobileMenuToggle();
  closeMobileMenu();
});

function mobileMenuToggle() {
  $('.mobile-nav-toggler').click(function() {
    $(this).toggleClass('active');
    $('body').toggleClass('mobile-nav-opened');
    return false;
  });
}

function closeMobileMenu() {
  $('html').click(function() {
    $('.mobile-nav-toggler').removeClass('active');
    $('body').removeClass('mobile-nav-opened');
  });
}
.mobile-nav-toggler {
  cursor: pointer;
  background: red;
  color: white;
  padding: 20px 30px;
  display: inline-block;
}

.mobile-nav-toggler.active {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mobile-nav-toggler">
  Mobile Nav Toggle
</div>
Shashank
  • 2,010
  • 2
  • 18
  • 38