简体   繁体   中英

Close dropdown on click anywhere

So I have the below code that works on clicking dropdowns and opening them, but then when I click on another dropdown, it doesn't close the previous one - How could I adjust my JS code to close the previous dropdown and keep the current dropdown open only?

 function dropdowns() { var dropdowns = document.querySelectorAll('.dropdown:not(.is-hoverable)'); if (dropdowns.length > 0) { dropdowns.forEach(function (el) { el.addEventListener('click', function (event) { event.stopPropagation(); el.classList.toggle('is-active'); }); }); document.addEventListener('click', function (event) { closeDropdowns(); }); } function closeDropdowns() { dropdowns.forEach(function (el) { el.classList.remove('is-active'); }); } }
 <link href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css" rel="stylesheet"/> <div class="dropdown is-clickable"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Dropdown button</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Dropdown item </a> <a class="dropdown-item"> Other dropdown item </a> <a href="#" class="dropdown-item is-active"> Active dropdown item </a> <a href="#" class="dropdown-item"> Other dropdown item </a> <hr class="dropdown-divider"> <a href="#" class="dropdown-item"> With a divider </a> </div> </div> </div>

Call closeDropdowns() before you toggle the is-active class in your event handler.

function dropdowns() {
    var dropdowns = document.querySelectorAll('.dropdown:not(.is-hoverable)');

    if (dropdowns.length > 0) {
        dropdowns.forEach(function (el) {
            el.addEventListener('click', function (event) {
                event.stopPropagation();

                closeDropdowns(); // <== HERE
                el.classList.toggle('is-active');
            });
        });

        document.addEventListener('click', function (event) {
            closeDropdowns();
        });
    }

    function closeDropdowns() {
        dropdowns.forEach(function (el) {
            el.classList.remove('is-active');
        });
    }
}

However, you should add a check to test if the dropdown is currently open and if so - skip the toggling of the class as this will close and reopen it again.

el.addEventListener('click', function (event) {
    const isActive = el.classList.contains('is-active');

    closeDropdowns();

    if (!isActive) {
        el.classList.toggle('is-active'); // or simply el.classList.add('is-active');
    }
    
    event.stopPropagation();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM