How to Create Accordion

The accordion is a component that organizes content within collapsable items. Accordion allows the display of only one collapsed item at a time. Accordions can toggle through a number of text blocks with a single click.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">

.active, .accordion: hover {

 background-color: #ccc; 

}

.panel {

 padding: 0 18px;

 display: none;

 background-color: white;

 overflow: hidden;

}

</style>

</head>

<body>

<h2>Accordion</h2>

<button class="accordion">Section 1</button>

<div class="panel">

 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>

</div>


<button class="accordion">Section 2</button>

<div class="panel">

 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>

</div>

<script>

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.display === "block") {

   panel. style.display = "none";

  } else {

   panel. style.display = "block";

  }

 });

}

</script>

</body>

</html>

Sign In or Register to comment.