Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to remove class if clicking outside of div or open/close button

I'm fairly new to JS and I can't quite figure out how to get this to work. Any help is very much appreciated! So I have a hamburger button that, when clicked, simultaneously toggles the animation of a slide-in panel and hamburger animation by adding a class to the panel and button. I have successfully added a click event to close the panel if user clicks anywhere outside of the panel but I can't get the hamburger button to remove the added classes as well. I'd like the user to have both options (click button or click outside of panel).

HTML:

<ul class="nav nav--right">
  <li class="v-button--slide-right" id="toggle-menu">
    <button class="mpp-menu-icon mpp-menu-icon--cross toggle-menu">
      <span class="toggle"></span>
      <span class="menu">menu</span>
    </button>
  </li>
</ul>

<nav id="menu--slide-right" class="nav menu--slide-right">
  <ul class="main-menu">
    <li><a href="/home">Home</a></li>
    <li><a href="/about">About</a></li>
  </ul>
</nav><!-- end slide menu -->

JS:

jQuery(document).ready(function($) {

    var openSidebar = function() {
        $('.menu--slide-right').addClass('is-active');
        $('.toggle-menu').addClass('is-active');
        $('#toggle-menu').addClass('toggle-close');
    }
    var closeSidebar = function() {
        $('.menu--slide-right').removeClass('is-active');
        $('.toggle-menu').removeClass('is-active');
        $('#toggle-menu').removeClass('toggle-close');
    }


    $('.toggle-menu').click(function(event) {
        event.stopPropagation();
        openSidebar();
    });

    $(document).click(function(event) {
        if (!$(event.target).closest('.menu--slide-right').length) {
            closeSidebar();
        }
    });
});

And here's a JSFIDDLE to demo what I have so far

like image 800
user2466010 Avatar asked Nov 19 '25 14:11

user2466010


1 Answers

Very simple fix - add an "open" variable which changes to true when the sidebar opens, and evaluate this variable in your click event handler.

Add the variable:

var open = false;

Add the variable mutators to your open and close functions:

var openSidebar = function(){
    $('.menu--slide-right').addClass('is-active');
    $('.toggle-menu').addClass('is-active');
    $('#toggle-menu').addClass('toggle-close');
    open = true; //This is the new part!
}

Then toggle which function to call on button click - I achieve this with a ternary operator:

$('.toggle-menu').click( function(event) {
    event.stopPropagation();
    var toggle = open ? closeSidebar : openSidebar;
    toggle();
});

Check the fiddle here

like image 60
jonny Avatar answered Nov 22 '25 02:11

jonny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!