Skip to content

Instantly share code, notes, and snippets.

@EscApp2
Forked from mmarienko/tabs.js
Created March 20, 2023 15:46
Show Gist options
  • Save EscApp2/9babff3789a60ac7eeba9646090e8530 to your computer and use it in GitHub Desktop.
Save EscApp2/9babff3789a60ac7eeba9646090e8530 to your computer and use it in GitHub Desktop.
Tabs plugin by vanilla JS
new class Tabs {
constructor() {
this.$wrapper;
this.$triggers;
this.$body;
this.init();
}
init() {
document.querySelectorAll('[data-tabs]').forEach((wrapper) => {
this.$wrapper = wrapper;
this.$triggers = [...wrapper.querySelector('[data-triggers]').children];
this.$body = [...wrapper.querySelector('[data-body]').children];
this.$triggers[0].classList.add('active');
this.$body[0].classList.add('active');
this.update();
this.addListenerClick();
this.addListenerHash();
});
}
update(event) {
const trigger = this.$wrapper.querySelector(`a[href="${window.location.hash}"]`);
const content = this.$wrapper.querySelector(`[data-id="${window.location.hash}"]`);
if (window.location.hash && trigger && content) {
this.$triggers.forEach((trigger) => {
trigger.classList.remove('active');
});
this.$body.forEach((content) => {
content.classList.remove('active');
});
trigger.classList.add('active');
content.classList.add('active');
}
sessionStorage.setItem("last-url", event?.oldURL);
}
addListenerClick() {
this.$triggers.forEach(trigger => {
trigger.addEventListener('click', this.changeTab.bind(this));
});
}
addListenerHash() {
window.addEventListener('hashchange', this.update.bind(this));
}
changeTab(event) {
event.preventDefault();
const trigger = event.target.closest('a[href^="#"]');
const content = this.$wrapper.querySelector(`[data-id="${trigger.hash}"]`);
this.$triggers.forEach(trigger => {
trigger.classList.remove('active');
});
this.$body.forEach(content => {
content.classList.remove('active');
});
trigger.classList.add('active');
content.classList.add('active');
history.replaceState(undefined, undefined, trigger.hash)
}
};
<div class="example__tabs" data-tabs>
<div class="example__triggers" data-triggers>
<a href="#content-1" class="example__tab">
Tab 1
</a>
<a href="#content-2" class="example__tab">
Tab 2
</a>
</div>
<div class="example__body" data-body>
<div class="example__content" data-id="#content-1">
Content 1
</div>
<div class="example__content" data-id="#content-2">
Content 2
</div>
</div>
</div>
.example__tab {
&.active {
text-decoration: underline;
}
}
.example__content {
display: none;
&.active {
display: block;
}
}

This is plugin which makes work with layout your project easier.

Anything you need is set needed data-attributes.

  • data-tabs - main container
  • data-triggers - container for header
  • data-body - container for content
  • data-id - unique identificator

Also need link with attribute href with set unique identificator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment