I have simple jquery dropdown with below code. It’s working properly. When I click the menu, ex: Projects then the dropdown will show. Now I need to close the dropdown when I click again the Projects then if I click again it will show the dropdown. Is there any way how to do that?
$(".dropdown-toggle").on("click", function(e) {
e.stopPropagation();
$(".dropdown-menu").removeClass("active");
$(this).siblings(".dropdown-menu").addClass("active");
});
.dropdown-menu {
min-width: 10rem;
margin-top: 10px;
background: #ffffff;
border-radius: .25rem;
padding: .5rem 0;
visibility: hidden;
opacity: 0;
-webkit-box-shadow: 0 3px 3px rgba(0,0,0,0.2);
-moz-box-shadow: 0 3px 3px rgba(0,0,0,0.2);
box-shadow: 0 3px 3px rgba(0,0,0,0.2);
}
.dropdown-menu.active {
visibility: visible;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="dropdown">
<a class="dropdown-toggle" id="projects">Projects</a>
<div class="dropdown-menu anim-1" data-target="projects">
<a class="dropdown-item" href="#">ABC</a>
<a class="dropdown-item" href="#">DEF</a>
</div>
</li>
<li class="dropdown">
<a class="dropdown-toggle" id="products">Products</a>
<div class="dropdown-menu anim-1" data-target="products">
<a class="dropdown-item" href="#">GHI</a>
<a class="dropdown-item" href="#">JKL</a>
<a class="dropdown-item" href="#">MNO</a>
</div>
</li>
</ul>
2
Answers
The easiest option if you’re using jQuery would be to use toggleClass() which will add or remove "active" class depending on it’s presence.
https://www.w3schools.com/jquery/html_toggleclass.asp
Filter the
$(".dropdown-menu")
before remove.active