Skip to content
Advertisement

Close Dropdown when other Dropdown is toggled active

i am trying to close let´s say Dropdown A automatically, when Dropdown B gets classList.toggle("active) (in this case i toggle the ClassList with a Click)

I can open (classList.toggle("active)) and close (classList.toggle("inactive)) it manually, but i want to close it automatically.

Right now i got this:

function dropdown() {

    let employerBranding = document.querySelector(".employer-branding");
    let marketing = document.querySelector(".marketing");
    let corporateOverall = document.querySelector(".corporate-overall");
    let technicalData = document.querySelector(".technical-data");

    let categoryModules = [employerBranding, marketing, corporateOverall, technicalData];
    let categoryDropdown = $(".category-dropdown");


    for (let i = 0; i < categoryModules.length; i++) {

        categoryModules[i].addEventListener("click", function () {
            categoryDropdown.slideDown();
        });

    }

}

dropdown();

The Problem is now: when i click on one of the 4 Modules of course it opens all of the Dropdowns. How can i trigger the correct Dropdown to the correct Module, so only one (the one below the clicked Module) opens up && How can i add with another click a .slideUp() to slide it up again?

Advertisement

Answer

After a little while a came up with this solution

function closeDropdown() {

    // let employerBrandingDropdown = document.querySelector(".employer-branding-dropdown");
    let employerBrandingDropdown = $('.employer-branding-dropdown');
    let marketingDropdown = $(".marketing-dropdown");
    let corporateOverallDropdown = $(".corporate-overall-dropdown");
    let technicalDataDropdown = $(".technical-data-dropdown");

    let dropdownArray = [employerBrandingDropdown, marketingDropdown, corporateOverallDropdown, technicalDataDropdown];

    window.addEventListener('mouseup', function (event) {
        for (let i = 0; i < dropdownArray.length; i++) {
            let categoryDropdown = dropdownArray[i];
            if ($(event.target !== categoryDropdown) && $(event.target).parent() !== categoryDropdown) {
                $(categoryDropdown).stop().slideUp();
            }
        }
    })
}

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement