Introduction
Recently, I used a useful widget in my web application which is called Accordion. In the older version of HTML, to implement Accordion, we needed to implement a lot of stuff like HTML, CSS and JavaScript code too for allowing the toggle effect.
But HTML 5 has this tag which can work similarly but in an effective way. In this tutorial, we are going to see the difference between both the old and the new accordion widget.
HTML 5 Accordion
To use HTML 5 Accordion, there is a new HTML tag, <details>, and it is used to add the accordion into our HTML page.
- <details>
- ...
- </details>
And to display the label along with the accordion, we are going to use the <summary> tag which is used to display a caption or a description.
- <summary>
- This is simple summary
- </summary>
Accordion using an older approach
If you have used an older approach to develop the accordion, then you must be aware of the excessive time it takes. Also, you must know that we need to apply an additional JavaScript code so that we can get the toggle effect. You can find the example below.
- <html>
- <head>
- <title>Manav - HTML Old Accordian Demo</title>
- <style>
- .accordion {
- background-color: #eee;
- color: #444;
- cursor: pointer;
- padding: 18px;
- width: 100%;
- border: none;
- text-align: left;
- outline: none;
- font-size: 15px;
- transition: 0.4s;
- }
- .active,
- .accordion:hover {
- background-color: #ccc;
- }
- .panel {
- padding: 0 18px;
- display: none;
- background-color: white;
- overflow: hidden;
- }
- </style>
- </head>
- <body>
- <h2>HTML Old Accordian</h2>
- <button class="accordion">Section 1</button>
- <div class="panel">
- <p>This is section 1</p>
- </div>
- <button class="accordion">Section 2</button>
- <div class="panel">
- <p>This is section 2</p>
- </div>
- <button class="accordion">Section 3</button>
- <div class="panel">
- <p>This is section 3</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>

Rafiki CaiPosted Jun 21, 2020, 2:53 PM
Greetings. Thanks, Manav, for this tutorial. I'm trying to embed this accordion; but am stumped on how to control the width and height of it. (See example here: test.votehisassout.org)
Rushi MehtaPosted Nov 1, 2018, 6:36 AM
Nice Explained Article