I'm currently exploring a new approach to creating Javascript tabs by utilizing data attributes instead of IDs to connect the tab with its content.
Here's the concept in action:
- When clicking on a
, it should add the class<button class="tab" data-tab-trigger="1">
is-active
and remove any existingis-active
classes from other buttons - The value of
data-tab-trigger
should match the value ofdata-tab-content
on the corresponding
and add the class<div class="tab-content" data-tab-content="1">
is-open
to it - The
is-active
class indicates the active tab, whileis-open
displays the related tab content
Here's the Javascript code I've been working on, but it's not behaving as expected:
var tabTriggerBtns = document.querySelectorAll('.tabs li button');
tabTriggerBtns.forEach(function(tabTriggerBtn, index){
tabTriggerBtn.addEventListener('click', function(){
var tabTrigger = this;
var tabTriggerData = tabTrigger.getAttribute('data-tab-trigger');
var tabContent = document.querySelector('.tab-content');
var currentTabData = document.querySelector('.tab-content[data-tab-content="' + tabTriggerData + '"]').classList.add('is-open');
if(tabContent !== currentTabData) {
tabContent.classList.toggle('is-open');
}
if(tabTrigger.classList.contains('is-active')) {
tabTrigger.classList.remove('is-active');
}
else {
tabTriggerBtn.classList.remove('is-active');
tabTrigger.classList.add('is-active');
}
});
});
You can view the ongoing script on Codepen: https://codepen.io/abbasarezoo/pen/752f24fc896e6f9fcce8b590b64b37bc
I'm struggling to identify the issue here. While I'm comfortable with jQuery, I'm still learning vanilla JS, so any guidance would be greatly appreciated.