This is a simple example of my HTML page, I have navbar with a dropdown menu display: 'none'
, and when I click on <li class="main-ul-li clickToDropDown">Example</li>
it display the menu display: 'block'
...
Now my question is: How can I hide the menu again when I click outside of it (outside of the li and the div)?
My code is 100% vanilla JavaScript
And thank you!
const dropdown_function = () => {
const dropdown_menu = document.querySelector('.dropdown-menu');
const dropdown_li = document.querySelector('.clickToDropDown');
dropdown_li.addEventListener('click', () => {
dropdown_menu.style.display = 'block';
});
}
dropdown_function();
ul {
list-style: none;
}
.main-ul {
display: flex;
align-items: center;
}
.main-ul-li {
margin:10px 20px;
cursor: pointer;
}
.dropdown-menu {
position: absolute;
top: 60px;
display: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<header>
<nav> <!-- Navbar -->
<ul class="main-ul"> <!-- ul -->
<li class="main-ul-li clickToDropDown">Example</li> <!-- li -->
<div class="dropdown-menu"> <!-- dropdown menu -->
<ul>
<li>Example1</li>
<li>Example2</li>
<li>Example3</li>
</ul>
</div>
<li class="main-ul-li">Example</li>
<li class="main-ul-li">Example</li>
</ul>
</nav>
</header>
</body>
</html>