Reputation: 388
I have some dynamic contents like sort of a news-feed and each element has a dropdown menu. I am able to toggle the dropdown-menu of the exact element I click on and when I click outside or anywhere else on the window it closes the menu which is nice. but problem arise when I click on another dropdown element. The previously clicked menu doesn't close instead it stays on the same page.
what I am trying to say is when I click multiple dropdown elements, I have them all showing, it only closes or disappears when I click outside of element.
For instance When I click on dropdown-1, then click on dropdown-2, they both display at the same window. How do I close dropdown 1 while dropdown 2 is open instead of having them both open.
How can I toggle each dropdown as I click. I am unable to attach video to this post, but I have added an image to help clarify my question.
This is an example of my JQuery code to toggle dropdown.
/* toggle dropdown options */
$(document).on("click", ".dropdown-toggle", function (e) {
e.stopPropagation();
$(this).siblings().toggleClass('show');
});
/* // Close the dropdown if the user clicks outside of it */
$(window).click(function (e) {
if (!e.target.matches('.dropbtn') ) {
var dropdowns = $('.dropdown-content');
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if ($(openDropdown).hasClass("show") ) {
$(openDropdown).removeClass("show");
}
}
}
});
Upvotes: 1
Views: 1631
Reputation: 388
I have been able to solve this problem.
what I did was to hide all divs that may be visible then toggle the dropdown I clicked to show its content.
$(document).on("click", ".dropdown-toggle", function (e) {
e.stopPropagation();
// hide all dropdown that may be visible
var i;
var dropdowns = $('.dropdown-content');
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if ($(openDropdown).hasClass("show")) {
$(openDropdown).removeClass("show");
}
}
// toggle the dropdown
$(this).siblings().toggleClass('show');
});
Upvotes: 1