jQuery Effects

Write jQuery code to show and hide a panel with one button

Description: One button must open the panel if it is closed, and close it if it is open.

Hint:

  • Use .toggle() or .slideToggle().

HTML of the page

<button id="btn">Open / Close</button>
<div id="panel" style="display:none">Panel content</div>

Solution

$('#btn').on('click', function () {
  $('#panel').slideToggle(300);
});

$('#btn').click();
console.log('after click 1: ' + $('#panel').css('display'));
$('#btn').click();
console.log('after click 2: ' + $('#panel').css('display'));
Console output

after click 1: block
after click 2: none

How it works

  • slideToggle() slides the panel down if it is hidden, and up if it is visible.
  • The panel starts hidden, so the first click opens it.

Read Fade and Slide Effects.

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.

Write jQuery code to make simple tabs

Description: There are three tab buttons. Clicking one must show only its content and mark the button as active.

Hint:

  • Link each button to its content with a data-tab attribute.

HTML of the page

<div id="tabs">
  <button class="tab active" data-tab="t1">Tab 1</button>
  <button class="tab" data-tab="t2">Tab 2</button>
  <button class="tab" data-tab="t3">Tab 3</button>
</div>
<div id="t1" class="content">Content 1</div>
<div id="t2" class="content" style="display:none">Content 2</div>
<div id="t3" class="content" style="display:none">Content 3</div>

Solution

$('.tab').on('click', function () {
  $('.tab').removeClass('active');
  $(this).addClass('active');

  $('.content').hide();
  $('#' + $(this).data('tab')).show();
});

$('.tab').eq(2).click();
$('.content').each(function () {
  console.log(this.id + ': ' + $(this).css('display'));
});
Console output

t1: none
t2: none
t3: block

How it works

  • The data-tab value is the id of the content to show.
  • First all contents are hidden, then the right one is shown.

Read CSS Classes and Effects.