Home > Enterprise >  Implement toggle in dropdown using JavaScript
Implement toggle in dropdown using JavaScript

Time:01-16

I have few dropdown lists and the common element in all is the role="list". I would like to implement toggle when I click on one dropdown, it closes the other open dropdown.

<div id="dropdownList1"  aria-multiselectable="false" role="list"></div>

<div id="dropdownList2"  aria-multiselectable="false" role="list"></div>

<div id="dropdownList3"  aria-multiselectable="false" role="list" ></div>

CodePudding user response:

You can use JavaScript to achieve this behavior:

// Get all the dropdown elements with the role of "list"
let dropdownLists = document.querySelectorAll('[role="list"]');

// Add a click event listener to each dropdown
dropdownLists.forEach(dropdown => {
    dropdown.addEventListener('click', function() {
        // Close all other dropdowns when one is clicked
        dropdownLists.forEach(otherDropdown => {
            if (otherDropdown !== this) {
                otherDropdown.style.display = 'none';
            }
        });
    });
});

This code will select all elements that have a role of "list" using querySelectorAll and will add a click event listener to each one. When one of the dropdowns is clicked, the event listener will close all other dropdowns by setting their display property to none.

You can also use toggle() function to toggle the display property of the element.

dropdown.addEventListener('click', function() {
    // Close all other dropdowns when one is clicked
    dropdownLists.forEach(otherDropdown => {
        if (otherDropdown !== this) {
            otherDropdown.style.display = 'none';
        }
    });
    this.classList.toggle('open');
});

Here, when you click on a dropdown, it will toggle the class 'open' to the clicked dropdown and close all other open dropdowns. And you can use css to define the styling for open class.

.open {
    display: block;
}

CodePudding user response:

check this out : add onclick="closeOthers(this)" to all dropdown items and here is the function :

function closeOthers(selected_dd){    $.each($('.jqx-listbox[role="List"]'),function(i,v){
     $(v).removeClass('open');//close all
    });
$(selected_dd).addClass('open'); //here is how to select the item u want, then u can open it as u want
}

consider that i made open class by myself... you can use any ather logic!

  • Related