Create JavaScript Accordion

JavaScript:

const accordionSections = document.querySelectorAll(".accordion");
accordionSections.forEach((accordion) => {
	accordion.onclick = function () {
		this.classList.toggle("is-open");

		let content = this.getElementsByClassName("accordion-content")[0];;
		//console.log(content);
		if (content.style.maxHeight) {
		  //this is if the accordion is open
		  content.style.maxHeight = null;
		} else {
			//if the accordion is currently closed
			content.style.maxHeight = content.scrollHeight + "px";
			//console.log(content.style.maxHeight);
		}
	};
});

HTML

<link rel='stylesheet'  href='https://fonts.googleapis.com/icon?family=Material+Icons' media='all' />
<div class="accordion">
	<div class="summary">Title 1</div>							
	<div class="accordion-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sed eros ac leo ultricies interdum sit amet et nunc.</div>											</div>
<div class="accordion">
	<div class="summary">Title 2</div>							
	<div class="accordion-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sed eros ac leo ultricies interdum sit amet et nunc.</div>											</div>
<div class="accordion">
	<div class="summary">Title 3</div>							
	<div class="accordion-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sed eros ac leo ultricies interdum sit amet et nunc.</div>											</div>

CSS:

.accordion {
    cursor: pointer;
    position: relative;
}
.accordion:before {
    font-family: "Material Icons";
    content: "\e5e1";
    display: inline-block;
    position: absolute;
    top: 22px;
}
.accordion .summary {
    padding-left: 24px;
}
.accordion.is-open:before {
    transform: rotate(90deg);
}
.accordion:hover,
.accordion.is-open {
}
.accordion-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-in-out;
}

Leave a Reply

Your email address will not be published. Required fields are marked *