I have successfully implemented a menu that closes (removes the added class) when clicking outside the menu button area.
Although it is working fine, I am unsure if my code is correct. My understanding is that the click outside functionality should only be triggered when the .newClass is added to the div. How can I make this adjustment? I am relatively new to JavaScript.
var b = document.getElementById("menu");
document.addEventListener("mouseup", function(event) {
var clickOnMenu = b.contains(event.target);
if (clickOnMenu) {
b.classList.toggle("newClass");
} else {
b.classList.remove("newClass");
}
});
div.box {
margin: auto;
padding: 1em;
max-width: 6em;
background: rgba(0, 0, 0, 0.6);
text-align: center;
color: white;
transition: .2s ease-in-out;
cursor: pointer;
}
div.box:hover {
background: rgba(0, 0, 0, 0.7);
}
div.newClass {
padding-bottom: 100px;
}
<div id="menu" class="box">Menu</div>