I am seeking assistance with implementing a Javascript onclick Dropdown Menu. The current issue I am facing is that when one menu is opened and another menu is clicked, the previous menu remains open. My desired solution is to have the previously open menu close automatically when a new menu is opened.
<!DOCTYPE HTML>
<html>
<head>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
}
.navbar {
width: 100%;
padding: 0 10% 0 10%;
overflow: hidden;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}
.dropbtn {
font-size: 16px;
border: none;
outline: none;
padding: 21.5px 20px;
background-color: inherit;
margin: 0;
cursor: pointer;
font-weight: bolder;
color: #2d3436;
}
.dropdown {
float: left;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #fff;
min-width: 460px;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
height: 450px;
}
.show {
display: block
}
</style>
</head>
<body>
<div class="navbar">
<div class="dropdown">
<button onclick="my1Function()" class="dropbtn dropbtn1">Dropdown <i class="fas fa-caret-down"></i></button>
<div id="myDropdown1" class="dropdown-content dropdown-content1">
</div>
</div>
<div class="dropdown">
<button onclick="my2Function()" class="dropbtn dropbtn2">Dropdown <i class="fas fa-caret-down"></i></button>
<div id="myDropdown2" class="dropdown-content dropdown-content2">
</div>
</div>
<div class="dropdown">
<button onclick="my3Function()" class="dropbtn dropbtn3">Dropdown <i class="fas fa-caret-down"></i></button>
<div id="myDropdown3" class="dropdown-content dropdown-content2">
</div>
</div>
</div>
<script>
function my1Function() {
document.getElementById("myDropdown1").classList.toggle("show");
}
function my2Function() {
document.getElementById("myDropdown2").classList.toggle("show");
}
function my3Function() {
document.getElementById("myDropdown3").classList.toggle("show");
}
window.onclick = 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');
}
}
}
}
</script>
</body>
</html>