Reputation: 138
https://jsfiddle.net/wwx100f8/69/
I am trying to create an expandable/collapsable accordion to hold restaurant food options, a digital menu similar to Just-Eat or Hungry House.
Using W3Schools, I have tried to implement the Animated Accordion to make this digital food menu. https://www.w3schools.com/howto/howto_js_accordion.asp
As you can see in my code, I have attempted to 'nest' the <button class="accordion">
within another.
However, the nested accordion once expended, does not then expand it's parent container. This results in the child accordion's content being hidden or cut off.
This issue is resolved by collapsing the parent accordion, after the child accordion has been opened. But this is inconvenient for the user.
I think I need some way to set the css so that the accordion containers fit around the child content. They appear to be fixed until clicked on.
I'm also open to any suggestions about how else I may achieve this 'digital menu'.
https://jsfiddle.net/wwx100f8/69/
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active, .accordion:hover {
background-color: #ccc;
}
.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<button class="accordion">Section 1</button>
<div class="panel">
<p>The Text in Section 1</p>
<button class="accordion">Section 2</button>
<div class="panel">
<p>The Text in Section 2</p>
</div>
</div>
Upvotes: 0
Views: 1707
Reputation: 605
instead of setting an absolute value for max-height
of your div.panel
, try setting max-height
to initial
, like this.
however, doing that breaks your animation, you can either switch to using jquery for animation (.slideUp
/.slideDown
or .slideToggle
) which doesn't have this issue, or try some trickery with timers: https://jsfiddle.net/wwx100f8/80/
Upvotes: 3