JSFiddle - React, Tailwind, and code Playground
HTML
<nav id="menus">
<div class="menu" id="menu1">
<a class="menu-button" href="#menu">Menu</a>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
</div>
<div class="menu" id="menu2">
<a class="menu-button" href="#menu2">Menu 2</a>
<ul>
<li><a href="#account">My account</a></li>
<li><a href="#logout">Logout</a></li>
</ul>
</div>
</nav>
<section id="content">
<p>Observe the intended behavior first. Click Menu, then Home, then Menu 2, then anywhere in these paragraphs.</p>
<p>At most, one menu should be open. Clicking anywhere not in the menu should collapse the menu.</p>
<p>Then change the code so `behaveAsIntended` is set to false</p>
</section>
CSS
.menu, section {
padding: 10px;
}
#menu1 {
background-color: #9f9;
}
#menu2 {
background-color: #99f;
}
section {
background-color: #f99;
}
ul {
padding-left: 10px;
display: none;
}
.menu.active ul {
display: block;
}
JavaScript
var menus = $('#menus');
// toggle menu by clicking menu button
menus.on('click', '.menu-button', function() {
var self = $(this);
self.closest('.menu')
.toggleClass('active')
.siblings().removeClass('active')
;
self.blur(); // prevent focus styles in MSIE7
return false; // prevent hash change
});
$(document).click(function(e) {
menus.children('.menu').each(function() {
var self = $(this);
var behaveAsIntended = true; // toggle this to demonstrate the bug
var remove = behaveAsIntended
? !self.find(e.target).length && !self.is(e.target)
: !self.find(e.target).andSelf().filter(e.target).length
;
if (remove) self.removeClass('active');
});
});