Home > OS >  Opening and closing dropdown in html
Opening and closing dropdown in html

Time:07-20

When I click on buttons nothing is happening. I am trying to make them open and close. How can I solve this?werrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr

HTML

    <div >
    <img src="assets/images/placeholder-logo.svg">

    <li ng-repeat="item in data" ng-if="dataLoaded">
        <button >{{item.streamName}}
            <i ></i>
        </button>
        <div >
            <ul>
                <li ng-repeat="element in item.apps">
                    <button >{{element.appName}}
                        <i  ng-if="element.sheets.length"></i>
                    </button>
                    <ul>
                        <li ng-repeat="sheet in element.sheets">
                            <button >{{sheet.sheetName}}
                            </button>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </li>
</div>

JAVASCRIPT

var dropdown = document.getElementsByClassName("dropdown-btn");
            var i;

            for (i = 0; i < dropdown.length; i  ) {
            dropdown[i].addEventListener("click", function() {
                this.classList.toggle("active");
                var dropdownContent = this.nextElementSibling;
                if (dropdownContent.style.display === "block") {
                dropdownContent.style.display = "none";
                } else {
                dropdownContent.style.display = "block";
                }
            });
            } 

CodePudding user response:

Your code is working, but it will hide the content area only after the second click on the button because the initial value dropdownContent.style.display is empty string, but you check if it's equals to "block".

So the first click on the button set the content area to display: block.

You need to change the check to dropdownContent.style.display === ""

var dropdown = document.getElementsByClassName("dropdown-btn");
var i;

for (i = 0; i < dropdown.length; i  ) {
    dropdown[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var dropdownContent = this.nextElementSibling;
        if (dropdownContent.style.display === "block" || dropdownContent.style.display === "") {
            dropdownContent.style.display = "none";
        } else {
            dropdownContent.style.display = "block";
        }
    });
} 
  • Related