jQuery Tabs Example
Tabs show one content block at a time. The tab buttons and the content blocks are connected with a data attribute.
HTML
<div class="tabs">
<button class="tab-btn active" data-target="#about">About</button>
<button class="tab-btn" data-target="#course">Courses</button>
<button class="tab-btn" data-target="#contact">Contact</button>
<div id="about" class="tab-panel">About us text</div>
<div id="course" class="tab-panel" style="display:none">Course list</div>
<div id="contact" class="tab-panel" style="display:none">Contact details</div>
</div>
CSS
.tab-btn { padding: 8px 14px; border: 1px solid #ccc; background: #f5f5f5; cursor: pointer; }
.tab-btn.active { background: #fff; border-bottom-color: #fff; font-weight: bold; }
.tab-panel { border: 1px solid #ccc; padding: 12px; }
jQuery code
$('.tab-btn').on('click', function () {
var $btn = $(this);
$('.tab-btn').removeClass('active');
$btn.addClass('active');
$('.tab-panel').hide();
$($btn.data('target')).fadeIn(150);
});
$('.tab-btn').eq(1).click();
$('.tab-panel').each(function () {
console.log(this.id + ': ' + $(this).css('display'));
});
Console output
about: none
course: block
contact: none
How it works
- The
data-targetattribute has the selector of the panel to show. - All panels are hidden first, and then only the chosen panel is shown with
fadeIn(). - The active class is moved to the clicked tab.
Note:
You can also open a tab from the address (the hash) with location.hash. For a plain JavaScript version see the code JavaScript Tabs without jQuery.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |