DEV Community

Umapreethi Santhanakrishnan
Umapreethi Santhanakrishnan

Posted on

Accordion using Html,Css,Js

Fifth day of my 100 days of code.

Html Code:

We have to create buttons and give contents below in div.

<h1>Accordion</h1>
    <h3>Click the button</h3>
    <div class="accordion">
      <button type="button" class="acc">What is Html?</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>
    </div>

    <div class="accordion">
      <button type="button" class="acc">What is CSS?</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>
    </div>
Enter fullscreen mode Exit fullscreen mode

Js code:

Access your button by using Classname and add eventlistener 'click' to all button.
Access your content by using nextSiblingElement and write the condition to display the content.

let acc = document.getElementsByClassName('acc');

for(let i=0; i< acc.length; i++){
    acc[i].addEventListener('click', function() {
        this.classList.toggle("active");
        let panel = this.nextElementSibling;
        if(panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    })
}
Enter fullscreen mode Exit fullscreen mode

Css Code:

Add the plus and minus sign using before property.

body {
  height: 100vh;
  background-color: #eee;
}

button {
  text-align: left;
  padding: 10px;
  margin-right: 5px;
  cursor: pointer;
  width: 50%;
  border-color: 1px solid #ccc;
}

button::before {
  content: "+";
  padding: 10px;
}

.active {
  background-color: #2c2b2b;
  color: #fff;
}
.active::before {
  content: "-";
  padding: 10px;
}

.panel {
  display: none;
  width: 50%;
 padding-left: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)