Question:
I want to make a menu that opens when you click on a button and closes when you click on any part of the screen. The problem is that the menu closes when clicked anywhere other than the open button. According to my idea, after opening the menu, the class of the button is removed and it should become inactive, which means it becomes the same as any part of the document, but for some reason this does not happen. What's my mistake?
$(document).ready(function() {
$(hidden).slideUp();
$('.switch').click(function() {
$(hidden).slideDown(300);
$('#drop-but').removeClass('switch');
return false;
});
$(document).click(function() {
$(hidden).slideUp(300);
$('#drop-but').addClass('switch');
});
});
Answer:
As an option:
$(function() {
$('.menu-wrap').on('click', function() {
var $this = $(this);
if ($this.hasClass('active')) {
$this.removeClass('active');
$(document).off('click.menu');
} else {
$this.addClass('active');
$(document).on('click.menu', function(e) {
if ($(e.target).closest('.menu-wrap').length === 0) {
$('.menu-wrap').removeClass('active');
$(document).off('click.menu');
}
});
}
});
});
.menu-wrap {
position: relative;
width: 100px;
}
.menu-title {
width: 100%;
border: 1px solid black;
cursor: pointer;
transition: all .5s;
}
.menu-wrap.active .menu {
visibility: visible;
opacity: 1;
}
.menu {
border: 1px solid black;
border-top: none;
width: 100%;
visibility: hidden;
opacity: 0;
transition: all .5s;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li:hover {
cursor: pointer;
background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu-wrap">
<div class="menu-title">
menu toogle
</div>
<div class="menu">
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
</div>
</div>