var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { /* Toggle between adding and removing the "active" class, to highlight the button that controls the panel */ this.classList.toggle("active"); /* Toggle between hiding and showing the active panel */ var panel = this.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; } else { panel.style.display = "block"; } }); }
JavaScript accordion example body { font-size: 80%; font-family: ‘Lucida Grande’, Verdana, Arial, Sans-Serif; } .accordionItem h2 { margin: 0; font-size: 1.1em; padding: 0.4em; color: #fff; background-color: #944; border-bottom: 1px solid #66d; } .accordionItem h2:hover { cursor: pointer; } .accordionItem div { margin: 0; padding: 1em 0.4em; background-color: #eef; border-bottom: 1px solid #66d; } .accordionItem.hide h2 { color: #000; background-color: #88f; } .accordionItem.hide div { display: none; } //<![CDATA[ var accordionItems = new Array(); function init() { // Grab the accordion items from the page var divs = document.getElementsByTagName( 'div' ); for ( var i = 0; i < divs.length; i++ ) { if ( divs[i].className == 'accordionItem' ) accordionItems.push( divs[i] ); } // Assign onclick events to the accordion item headings for ( var i = 0; i < accordionItems.length; i++ ) { var h2 = getFirstChildWithTagName( accordionItems[i], 'H2' ); h2.onclick = toggleItem; } // Hide all accordion item bodies except the first for ( var i = 1; i < accordionItems.length; i++ ) { accordionItems[i].className = 'accordionItem hide'; } } function toggleItem() { var itemClass = this.parentNode.className; // Hide all items for ( var i = 0; i < accordionItems.length; i++ ) { accordionItems[i].className = 'accordionItem hide'; } // Show this item if it was previously hidden if ( itemClass == 'accordionItem hide' ) { this.parentNode.className = 'accordionItem'; } } function getFirstChildWithTagName( element, tagName ) { for ( var i = 0; i

JavaScript accordion example

About accordions

JavaScript accordions let you squeeze a lot of content into a small space in a Web page.

This simple accordion degrades gracefully in browsers that don’t support JavaScript or CSS.

Accordion items

A JavaScript accordion is made up of a number of expandable/collapsible items. Only one item is ever shown at a time.

You can include any content you want inside an accordion item. Here’s a bullet list:

  • List item #1
  • List item #2
  • List item #3

How to use a JavaScript accordion

Click an accordion item’s heading to expand it. To collapse the item, click it again, or click another item heading.

Return to the JavaScript Accordion article