MindX
MindX

Reputation: 49

How to close navigation with outside click?

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

Upvotes: 0

Views: 717

Answers (1)

Alexander Nied
Alexander Nied

Reputation: 13623

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.

Upvotes: 1

Related Questions