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.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.