In this chapter, we will learn how to use JS/CSS to implement theaccordion collapseeffect.
Try it Yourself »
Basic HTML Code
Example
<button class="accordion">Example 1</button>
<div class="panel">
<p>Example -- Learning is not only technology, but also dreams!!!</p>
</div>
<button class="accordion">Example 2</button>
<div class="panel">
<p>Example -- Learning is not only technology, but also dreams!!!</p>
</div>
<button class="accordion">Example 3</button>
<div class="panel">
<p>Example -- Learning is not only technology, but also dreams!!!</p>
</div>
The following is theaccordion collapsestyles:
Example
/*Style for opening and closing the accordion panel*/
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
outline: none;
transition: 0.4s;
}
/*Set styles for click and hover on the option*/
.active, .accordion:hover {
background-color: #ccc;
}
/*Design styles for the accordion panel. Hidden by default*/
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
/*Set +, - signs*/
.accordion:after {
content: '\002B'; /*Unicode character + sign*/
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212"; /*Unicode character - sign*/
}
The following is theaccordion collapseJavaScript code:
Example
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";
}
});
}
Try it Yourself »