JavaScript Tabs without jQuery
Tabs show one panel of content at a time. You do not need jQuery: a few lines of plain JavaScript are enough.
HTML
<div class="tabs">
<button class="tab-btn active" data-tab="html">HTML</button>
<button class="tab-btn" data-tab="css">CSS</button>
<button class="tab-btn" data-tab="js">JavaScript</button>
</div>
<div id="html" class="tab-panel active">HTML gives the structure.</div>
<div id="css" class="tab-panel">CSS gives the style.</div>
<div id="js" class="tab-panel">JavaScript gives the behaviour.</div>
CSS
.tab-btn { padding: 8px 16px; border: 0; background: #eee; cursor: pointer; }
.tab-btn.active { background: #0073aa; color: #fff; }
.tab-panel { display: none; padding: 12px; border: 1px solid #ddd; }
.tab-panel.active { display: block; }
JavaScript
const buttons = document.querySelectorAll(".tab-btn");
const panels = document.querySelectorAll(".tab-panel");
buttons.forEach(button => {
button.addEventListener("click", () => {
// remove the active class from all
buttons.forEach(b => b.classList.remove("active"));
panels.forEach(p => p.classList.remove("active"));
// add it to the clicked tab and its panel
button.classList.add("active");
document.getElementById(button.dataset.tab).classList.add("active");
});
});
Output in the browser (the page after the CSS tab is clicked):
Output in the browser
CSS gives the style.
How it works
- Each button has a
data-tabattribute with the id of its panel. - Only the element with the class
activeis shown (display: block), the others are hidden. - On click, the code removes
activefrom all tabs and panels, and adds it to the chosen ones.
Related: HTML DOM and DOM EventListener.
Learn more about the similar topics:
| Tutorials |
|---|
| JavaScript Events |
| JavaScript HTML DOM |
| JavaScript DOM Manipulation |
| JavaScript HTML DOM EventListener |
| JavaScript Forms and Validation |
| Exercises & Assignments |
|---|
| Write a JavaScript program to change the text of a paragraph on button click |
| Write a JavaScript program to switch dark mode on and off |