Write jQuery code to make a simple accordion

Description: Clicking on a question must open its answer, and close the other open answers.

Hint:

  • Use .next(), .slideToggle() and .siblings() or .not().

HTML of the page

<div id="faq">
  <h3>Question 1</h3><p style="display:none">Answer 1</p>
  <h3>Question 2</h3><p style="display:none">Answer 2</p>
  <h3>Question 3</h3><p style="display:none">Answer 3</p>
</div>

Solution

$('#faq h3').on('click', function () {
  var $answer = $(this).next('p');
  $('#faq p').not($answer).slideUp();
  $answer.slideToggle();
});

$('#faq h3').eq(0).click();
$('#faq h3').eq(1).click();

$('#faq p').each(function (i) {
  console.log('Answer ' + (i + 1) + ': ' + $(this).css('display'));
});
Console output

Answer 1: none
Answer 2: block
Answer 3: none

How it works

  • The first click opens answer 1. The second click opens answer 2 and closes answer 1.
  • .not($answer) selects all the other answers.

Read Fade and Slide Effects.


Learn more about the similar topics:
Tutorials
jQuery Effects: hide, show and toggle
jQuery Fade and Slide Effects
jQuery animate() Method
jQuery Method Chaining and Callbacks
Exercises & Assignments
Write jQuery code to show and hide a panel with one button
Write jQuery code to make a simple accordion
Write jQuery code to make simple tabs
Interview Questions & Answers
What is method chaining in jQuery?
How do you hide and show an element in jQuery?
How do you use the animate() method in jQuery?
What is a callback function in jQuery and why is it needed in effects?
What is the difference between stop(), finish() and delay() in jQuery?