jqueryhtmltoggleclass

Toggle classes with jQuery by clicking button and clicking other element than selected


I'd like to toggle the drawer with the 'drawer-toggle'-button, as shown in the snippet.

The only problem is that when the drawer is opened, I want to close it also with by clicking outside the .drawer-div.

Anyone could help me with this one? There must be a more efficient way.

the .locked class is used for css purpose.

$(".drawer-toggle").click(function(e){
	$(".drawer").toggleClass('open');
	$(".main").toggleClass('locked');

	e.stopPropagation();
});

$(".main").click(function(){
	if ($(".drawer").hasClass('open')) {
		$(".drawer").toggleClass('open');
		$(".main").toggleClass('locked');
	}
});
body,
html {
  position: relative;
  height: 100%;
  width: 100%;
  margin: 0 auto;
  padding: 0;
}
*,
*:before,
*:after {
  box-sizing: border-box;
}
.locked {		
	overflow: hidden !important;
}
.drawer {
  position: fixed;
  background-color: $white;
  width: 200px;
  top: 0;
  bottom: 0;
  right: -200px;
  padding: 20px;
  border-left: 1px solid $border-color;
  transition: all 0.3s ease 0s;
}
.drawer.open {
  right: 0;
}
.drawer.open ~ .main {
  left: -200px;
}
.drawer.open ~ .main:after {
  content: ' ';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0,0,0,0.4);
  z-index: 900;
}
.main {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0;
  background-color: grey;
  transition: all 0.3s ease 0s;
}
.drawer-toggle {
  display: inline-block;
  padding: 10px;
  background-color: green;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="drawer">
  <a class="drawer-toggle">toggle</a>
  <ul>
    <li><a href="#">Menu item</a></li>
  </ul>
</div>
<div class="main">
  <a class="drawer-toggle">toggle</a>
</div>


Solution

  • Add a listener on the document and inside the handler check if the target is the drawer or a toggle button.

    $(document).on('click', function(event) {
      var $tgt = $(event.target)
      if (!$tgt.closest('.drawer').length && !$tgt.closest('.drawer-toggle').length && $('.drawer').hasClass('open')) {
        $(".drawer").removeClass('open');
        $(".main").removeClass('locked');
      }    
    });