The dropdown menu is getting open and closed both simultaneously after clicking the nav link.
I am trying to make a dropdown menu and it is getting closed by itself:
When I am trying to click on the dropdown, it is closing by itself, and I am not able to catch the problem.
The HTML, CSS and JavaScript code are as follows:
let dropdownLinks = document.querySelector(".nav-linkdrp");
let drpdwnMenu = document.querySelector(".drpdwn-menu");
function drpdwnMenuFunc() {
drpdwnMenu.classList.toggle("drpdwn-menu-active");
}
.navbar-nav {
display: flex;
gap: 2vw;
}
.nav-items {
list-style: none;
}
.drpdwn {
display: flex;
gap: 0.4vw;
align-items: center;
justify-content: center;
}
.drpdwn-menu {
display: none;
}
.drpdwn-menu-active {
z-index: 99;
display: flex;
position: absolute;
top: 100%;
flex-direction: column;
align-items: center;
background-color: white;
width: 10vw;
height: auto;
border: solid black 3px;
padding: 20px 20px;
}
.drpdwn-item {
list-style: none;
padding: 1vh 2vw 1vh 2vw;
}
.drpdwn-item a {
text-decoration: none;
font-weight: 500;
color: black;
}
.nav-links {
text-decoration: none;
color: black;
font-weight: 500;
font-size: 20px;
}
<ul class="navbar-nav">
<li class="nav-items"><a href="" class="nav-links">HOME</a></li>
<li onclick="drpdwnMenuFunc()" class="nav-items drpdwn">
<a href="" class="nav-links nav-linkdrp">LEARN</a>
<i class="ri-arrow-down-s-fill"></i>
<ul class="drpdwn-menu">
<li class="drpdwn-item"><a href="">ABOUT</a></li>
<li class="drpdwn-item"><a href="">FAQ</a></li>
<li class="drpdwn-item"><a href="">BLOGS</a></li>
</ul>
</li>
<li class="nav-items drpdwn">
<a href="" class="nav-links">DISCOVER</a>
<i class="ri-arrow-down-s-fill"></i>
</li>
<li class="nav-items"><a href="" class="nav-links">CONTACT</a></li>
</ul>
I was expecting a good dropdown.
2
Answers
When you click on the dropdown link, the click event triggers for both the dropdown link and the parent list item. This causes the dropdown menu to toggle open and then immediately close.
One way to solve this issue is by stopping the event propagation when clicking on the dropdown link. You can modify your JavaScript code as follows:
By calling event.stopPropagation() in the drpdwnMenuFunc function, it prevents the click event from propagating up to the parent elements. As a result, the dropdown menu should no longer close immediately after opening.
The problem is so simple & hidden.
You have used an anchor tag that reloads the page on click.
Just replace
<a href="" class="nav-links nav-linkdrp">LEARN</a>
with
<span class="nav-links nav-linkdrp">LEARN</span>
And along with this, I checked your CSS code. In your CSS code, add
position: relative;
in your.drpdwn
selector.