Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hellobrian/f99b48ad868afe4d0dbc to your computer and use it in GitHub Desktop.
Save hellobrian/f99b48ad868afe4d0dbc to your computer and use it in GitHub Desktop.
Vanilla JavaScript Tabs with visibility hidden/visible
<h1>JavaScript Tabs (<a href="https://gist.github.com/thisisbrianhan/f99b48ad868afe4d0dbc">gist</a>)</h1>
<div class="border">
<ul>
<li><a href="#" id="link-1">link 1</a></li>
<li><a href="#" id="link-2">link 2</a></li>
<li><a href="#" id="link-3">link 3</a></li>
</ul>
<div id="content-1" class="active">content-1</div>
<div id="content-2">content-2</div>
<div id="content-3">content-3</div>
</div>
<h2>Reference Links</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded">DOMContentLoaded</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for..in</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault">event.preventDefault()</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element.classList"></a>Element.classList</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element.id"></a>Element.id</li>
</ul>
/*document.addEventListener('DOMContentLoaded', function(){
console.log('DOM is fully loaded and parsed');*/
var tabs = {
sample1: document.getElementById('link-1'),
sample2: document.getElementById('link-2'),
sample3: document.getElementById('link-3')
}
var content = {
one: document.getElementById("content-1"),
two: document.getElementById("content-2"),
three: document.getElementById("content-3")
}
for (tab in tabs) {
// console.log(tabs[tab]);
tabs[tab].addEventListener('click', function(event) {
event.preventDefault();
var $this = this;
clearSelected();
$this.classList.add("selected");
// console.log(this.id);
clearActive();
if ($this.id === "link-1") {
content.one.classList.add("active");
} else if ($this.id === "link-2") {
content.two.classList.add("active");
} else {
content.three.classList.add("active");
}
});
}
function clearSelected() {
for (tab in tabs) {
tabs[tab].classList.remove("selected");
}
}
function clearActive() {
for (element in content) {
content[element].classList.remove("active");
}
}
/*});*/
.border {
border: 1px solid black;
ul {
display: flex;
list-style-type: none;
li { margin-left: 10px; }
}
}
a {
border: 1px solid transparent;
&.selected {
border: 1px solid black;
}
}
#content-1,
#content-2,
#content-3 {
visibility: hidden;
&.active {
background-color: orange;
visibility: visible !important;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment