jQuery Accordion Example
An accordion shows a list of headings, and only one panel is open at a time. This code uses slideToggle() and slideUp().
HTML
<div class="accordion">
<h3 class="acc-head">What is jQuery?</h3>
<div class="acc-body" style="display:none">jQuery is a JavaScript library.</div>
<h3 class="acc-head">Is it free?</h3>
<div class="acc-body" style="display:none">Yes, it is free and open source.</div>
<h3 class="acc-head">Which version to use?</h3>
<div class="acc-body" style="display:none">The latest 3.x or 4.x version.</div>
</div>
CSS
.acc-head { cursor: pointer; background: #f1f1f1; padding: 10px; margin: 0; border-bottom: 1px solid #ddd; }
.acc-head.open { background: #dbeafe; }
.acc-body { padding: 10px; border: 1px solid #ddd; border-top: 0; }
jQuery code
$('.acc-head').on('click', function () {
var $head = $(this);
var $body = $head.next('.acc-body');
$('.acc-head').not($head).removeClass('open');
$('.acc-body').not($body).slideUp(200);
$head.toggleClass('open');
$body.slideToggle(200);
});
// test: open the 2nd item, then the 3rd
$('.acc-head').eq(1).click();
$('.acc-head').eq(2).click();
$('.acc-body').each(function (i) {
console.log('Panel ' + (i + 1) + ': ' + $(this).css('display'));
});
Console output
Panel 1: none
Panel 2: none
Panel 3: block
How it works
.next('.acc-body')finds the panel that belongs to the clicked heading..not($body)selects all the other panels, and they are closed withslideUp().toggleClass('open')changes the style of the active heading, andslideToggle()opens or closes the panel.- The test clicks the second and then the third heading. The output shows that only the third panel stays open.
Note:
For a keyboard friendly accordion, use button elements inside the headings and add the aria-expanded attribute. See Fade and Slide Effects.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |