Learn how to create an accordion (collapsible content).
Accordion
Accordions are useful when you want to toggle between hiding and showing large amount of content:
Create An Accordion
Step 1) Add HTML:
<div class="accordion-div"><button class="accordion"><span class="faq__question-heading">Title1</span></button>
<div class="panel">
<p style="padding:18px 0;">description1</p>
</div>
<button class="accordion"><span class="faq__question-heading">Title2</span></button>
<div class="panel">
<p style="padding:18px 0;">description2</p>
</div>
<button class="accordion"><span class="faq__question-heading">Title3</span></button>
<div class="panel">
<p style="padding:18px 0;">description3</p>
</div>
</div>
Step 2) Add CSS:
Style the accordion:
/* Style the buttons that are used to open and close 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;
}
/* Add a background color to the button if it is clicked on (add the
.active class with JS), and when you move the mouse over it (hover) */
.active, .accordion:hover {
background-color: #ccc;
}
/* Style the accordion panel. Note:
hidden by default */
.panel {
padding: 0 18px;
background-color: white;
display: none;
overflow: hidden;
}
Step 3) Add JavaScript:
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
let active = document.querySelectorAll(".accordion-div .accordion.active");
for (let j = 0; j < active.length; j++) {
active[j].classList.remove("active");
active[j].nextElementSibling.style.maxHeight = null;
}
this.classList.toggle("active");
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
</script>
How To - Collapsibles/Accordion
Reviewed by webmission
on
11:36
Rating:
No comments:
Post a Comment