Mr. Bungle Mr. Bungle - 2 months ago 15
CSS Question

Have only one drop down panel open on click using HTML, JS, and CSS

I have a drop down menu list of links fixed on the left side of a web page I'm trying to build. I got the structure of the HTML and CSS here on w3 schools, but fit it to my page. I like the way it came out because it's a smooth transition of opening the panel to show the links, however because it's fixed, if all the drop down panels are open you can't scroll down the screen to see. I originally wanted to have it scroll if it became too long, but I would much rather have it where only one drop down panel is open at a time. I would like that functionality like here where I still keep the smooth transition of opening and closing panels. I'm still learning, so I don't know how to modify the code to do what I want so I was hoping someone can help me. I would like to stick with just HTML, JS, and CSS. Here's the core pieces I'm using in my page.

CSS

ul {position: fixed;}

li {
text-align: left;
display: block;
text-decoration: none;
}

li.drop-down {
cursor: pointer;
transition: 0s;
}

div.drop-down-panel {
max-height: 0;
overflow: hidden;
transition: max-height 0.5s ease-out;
}

a.panel {
text-align: left;
display: block;
text-decoration: none;
}


HTML

<ul>
<li class="drop-down">Header 1</li>
<div class="drop-down-panel">
<a class="panel" href="#link1">Link 1</a>
<a class="panel" href="#link2">Link 2</a>
</div>
<li class="drop-down">Header 2</li>
<div class="drop-down-panel">
<a class="panel" href="#link3">Link 3</a>
</div>
<li class="drop-down">Header 3</li>
<div class="drop-down-panel">
<a class="panel" href="#link4">Link 4</a>
<a class="panel" href="#link5">Link 5</a>
</div>
</ul>


JS

var acc = document.getElementsByClassName("drop-down");

for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}

Answer Source

Hope this helps:

<script>
   var acc = document.getElementsByClassName("drop-down");

    for (i = 0; i < acc.length; i++) {
        acc[i].onclick = function() {
            var panel = this.nextElementSibling;
            var maxHeight = panel.style.maxHeight;

            //Collapse all divs first
            var divs = document.getElementsByClassName("drop-down-panel");
            for (i = 0; i < divs.length; i++) {
                 divs[i].style.maxHeight = null;
            };

            if (maxHeight)
                panel.style.maxHeight = null;
            else
                panel.style.maxHeight = panel.scrollHeight + "px"; 
        }
    }
</script>