How to create an Accordion with CSS and JavaScript?

CSSWeb DevelopmentFront End Technology

To create an Accordion with CSS and JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.demo {
   background-color: #eee;
   cursor: pointer;
   padding: 25px;
   width: 100%;
}
.active, .demo:hover {
   background-color: #ccc;
   border: 2px;
   font-size: 14px;
}
.panel {
   padding: 0 18px;
   display: none;
   background-color: #F0F8FF;
      overflow: hidden;
}
</style>
</head>
<body>
<h2>Examination</h2>
<p>Following is the information on exams:</p>
<button class="demo">Admit Card</button>
<div class="panel">
   <p>Admit Card will release on 25th March.</p>
</div>
<button class="demo">Exam Date</button>
<div class="panel">
   <p>Exam will held on 30th March.</p>
</div>
<script>
var val = document.getElementsByClassName("demo");
var i;
for (j = 0; j < val.length; j++) {
   val[j].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>

Output

This will produce the following output −

On clicking any of the Button, the hidden info will be visible as shown below −

raja
Published on 03-Apr-2020 07:33:22
Advertisements