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
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?