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>
EDIT:
I've found the solution-
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';
<!--func added-->
document.addEventListener('mouseup', function(e) {
if (!dropdown_menu.contains(e.target)) {
dropdown_menu.style.display = 'none';
}
});
<!--/func added-->
});
}
You can add something like this:
document.addEventListener('click', function(event) {
var isClickInside = dropdown_li.contains(event.target);
if (isClickInside) {
//More Stuff
}
else {
dropdown_menu.style.display = 'none';
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.