/* I've ran into some trouble while trying to make a menu close when a user clicks outside of it, i watched a couple of tutorials but nothing seems to work right now it kinda works but now the actual closing button doesn't work anymore*/
const menuBtn = document.getElementById('hamburger');
const navToggle = document.getElementById('dropdown-content');
let x = false;
let menu = false;
function menuOpen() {
if(!x){
navToggle.classList.toggle('show');
menuBtn.classList.toggle('open');
x = true;
menu = true;
}else{
navToggle.classList.remove('show');
menuBtn.classList.remove('open');
x = false;
}
};
document.onmouseup = function() {
if(menu){
navToggle.classList.remove('show');
menuBtn.classList.remove('open');
x = false;
}
/*here's the html part*/
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no">
<title>new project</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Luxurious+Roman&family=Roboto+Mono:wght@100&display=swap" rel="stylesheet">
</head>
<body>
<div onclick="menuOpen()" id="hamburger">
<div class="menu-btn"></div>
</div>
</body>
</html>```
The key-point is using a global click-handler that checks the click-target and hides the menu when it's appropriate.
Here's an example:.
const btn = document.getElementsByTagName('button')[0];
const menu = document.getElementsByTagName('ul')[0];
// toggle visibility when the button is clicked
btn.onclick = () => menu.classList.toggle('active');
// hide the menu whenever there's a click not inside the menu or on the button
document.onclick = ({ target }) => {
if (
!(target === btn || target === menu || menu.contains(target))
) menu.classList.remove('active');
};
ul {
border: 1px solid black;
display: none;
}
ul.active {
display: block;
}
<button>toggle menu</button>
<ul>
<li>Home</li>
<li>Sub</li>
<li>Sub Two</li>
</ul>