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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.