JSFiddle - React, Tailwind, and code Playground
HTML
<div id="menu">
<ul>
<li>Alfa</li>
<li>Beta</li>
<li>Gama</li>
</ul>
</div>
<button type="button">Toggle menu</button>
CSS
#menu {
margin-left: -200px;
transition: margin-left 1s;
border: 2px solid #88f;
background-color: #ddf;
border-radius: 20px;
width: 220px;
}
#menu.aberto {
margin-left: 0px;
}
button {
margin-top: 50px;
padding: 10px;
}
JavaScript
function getClosest(el, selector) {
while (el && !el.matches(selector)) {
el = el.parentElement;
}
return el;
}
var menu = document.getElementById('menu');
var button = document.querySelector('button');
var aberto = false;
button.addEventListener('click', function(e) {
e.stopPropagation();
aberto = menu.classList.toggle('aberto');
});
window.addEventListener('click', function(e) {
var dentroMenu = aberto && getClosest(e.target, '#menu');
if (aberto && !dentroMenu) aberto = menu.classList.toggle('aberto');
});