I want to make it so when you click anywhere on the page it hides the dropdown menu and I want an animation when the dropdown opens and closes. I've tried multiple ways but none of them work. I want to make it so when you click anywhere on the page it hides the dropdown menu and I want an animation when the dropdown opens and closes. I've tried multiple ways but none of them work.
Here is the whole code:
Javascript:
function Dropdown() {
document.getElementById("myDropdown").classList.toggle("show");
}
event.stopPropagation = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./assets/css/NavBar.css">
<link rel="stylesheet" href="./assets/css/Dropdown.css">
<link rel="shortcut icon" href="./images/favicon.ico" />
<script src="https://kit.fontawesome.com/7615d16710.js" crossorigin="anonymous"></script>
<title>MusmanDev</title>
</head>
<body>
<header>
<a class="logo" href="#"><img class="logo" src="./images/logo.png" alt="MusmanDev"></a>
<nav>
<ul class="nav__links">
<li><a href="#">Blogs</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">Courses</a></li>
<li><a>|</a></li>
<li>
<div class="dropdown">
<script src="./assets/js/Dropdown.js"></script>
<i class="fa-solid fa-bolt fa-lg" class="dropbtn" onclick="Dropdown()"></i>
<div id="myDropdown" class="dropdown-content">
<a><i class="fa-solid fa-moon"></i> Dark Mode</a>
<a><i class="fa-solid fa-sun"></i> Light Mode</a>
<a><i class="fa-solid fa-display"></i> System</a>
</div>
</div>
</li>
<li><a href="#"><i class="fa-brands fa-github-square fa-xl"></i></a></li>
</ul>
</nav>
</header>
</body>
</html>
CSS:
.dropbtn {
background-color: #24252A;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
cursor: pointer;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.show {
display: block;
}