0

I would like to detect a click outside of the menu class .tab-nav-menu, on the rest of the window and add an event to close the menu with similar animation of closing.

// Menu
jQuery(function($) {
    $('.header-menu-toggle').on('click', function(e){
        e.preventDefault();
        $('.tab-nav-menu >ul >li').animate({
            opacity: 0
        }, 200).animate({
            bottom: '-25px'
        }, 50);

        if($('.tab-nav-menu').hasClass('tab-invisible') ){
            $('.tab-nav-menu').css({'right':'-1em'});
            $('.tab-nav-menu').removeClass('tab-invisible').addClass('tab-visible');
            $(this).find('.burg').addClass('activeBurg');
        }
        else{
            $('.tab-nav-menu').css({'right':'-100%'});
            $('.tab-nav-menu').removeClass('tab-visible').addClass('tab-invisible');
            $(this).find('.burg').removeClass('activeBurg');
        }
        var delay = 600;
        var duration = 400;
        if( $(".header-navigation-menu").hasClass("strip-header-menu") ){
            delay = 250;
        }
        $('.tab-nav-menu >ul >li').each(function(){
            $(this).delay(delay).animate({
                opacity: 1,
                bottom: 0,
            }, duration);
            delay += 150;
        });
    })
});

Thanks for your help

MindX
  • 49
  • 4
  • 1
    We do this by adding a click-handler on the `` tag and calling a function that, essentially, removes a class from menu and sub-menu items down the menu hierarchy. We don't use `.animate()` or such, we use straight CSS for menus showing/hiding and we just adjust the class(es) on the menu items. – Stephen P Mar 13 '17 at 20:35
  • you could still use animations and follow the above advice, just create a body click handler that finds the relevant classes in your menu, processes them, and animates them accordingly – robisrob Mar 13 '17 at 21:18
  • 1
    Possible duplicate of [Click outside menu to close in jquery](http://stackoverflow.com/questions/2868582/click-outside-menu-to-close-in-jquery) – AmericanUmlaut Mar 13 '17 at 22:30

1 Answers1

1

A simplified "on outside click" jQuery script:

$(document).ready(function () {

  $(document).on('click', function (e) {
    var clickedEl = $(e.target);
    var outsideClicker = $('#clicker');

    if ( !(clickedEl.is(outsideClicker)
 || outsideClicker.has(clickedEl).length > 0) ) { // I flipped this so you can just omit the else
      console.log('I clicked outside the target!'); // do whatever you need to do here-- maybe call a function that closes the menu...
    } else {
      console.log('all good'); // if you don't have an else just get rid of this
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

  <h1> A title </h1>
  <p> A paragraph and a <b id="clicker">thing <span>to</span> click </b></p>

</div>

You can extrapolate this for your purposes.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45