I recently encountered an issue with a drop-down navigation bar. When I have multiple drop-downs and click on one, it opens as expected. However, if I then proceed to click on another drop-down while the first one is already open, both of them remain open simultaneously. This behavior is not desired, so I am seeking guidance on how to resolve this problem.
Below is the code snippet that I am currently working with:
HTML:
<nav class="navbar">
<ul class="navbar-links">
<li class="navbar-link"><a href="#">Home</a></li>
<li class="navbar-link"><a href="#">About</a></li>
<li class="navbar-link dropdown">
<a href="#">
Projects
<i class="fa fa-caret-down" aria-hidden="true"></i>
</a>
<div class="dropdown-content">
<a href="#">Shanary</a>
<a href="#">Physics Solver</a>
<a href="#">A simple blog</a>
</div>
</li>
<li class="navbar-link dropdown">
<a href="#">
Projects
<i class="fa fa-caret-down" aria-hidden="true"></i>
</a>
<div class="dropdown-content">
<a href="#">Something else</a>
<a href="#">Text Editor</a>
<a href="#">A social Network</a>
</div>
</li>
</ul>
</nav>
CSS:
.navbar {
background-color: #3A506B;
border-bottom: 1px solid #cccccc;
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
}
.navbar-links {
margin: 0;
font-size: 16px;
list-style-type: none;
}
.navbar-link,
.dropdown-content a {
display: inline-block;
padding: 20px 0px;
transition: background 0.1s ease-in-out;
}
.navbar-link:hover,
.dropdown-content a:hover {
background: #3f5775;
}
.navbar-link a {
padding: 20px 10px;
color: #5DD39E;
text-decoration: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
top: 100%;
min-width: 160px;
padding: 10px;
z-index: 1;
background-color: #3A506B;
}
.dropdown-content a {
display: block;
}
body {
font-family: 'Open Sans', Arial, sans-serif;
background: #FFFFFF;
color: #16302B;
margin: 0px;
}
.visible {
display: block;
}
This is the JavaScript function I have implemented so far:
$('.dropdown').click(function() {
$(this).find('.dropdown-content').toggleClass('visible');
});
To view the JSFiddle demonstration, click here.
The issue persists in which both drop-downs remain open simultaneously without closing each other. Here is an illustration of the problem: