Reputation: 3
So I coded 4 tabs and boxes and I want to add the 'on' class to the tab I clicked on and the 'shown' class to the box with the matching number while removing the same classes from the tab and box that currently have the class. The code works but I wanted to add a variable (i) inside the event listener so that when I click on tabsArray[i] the variable is inserted into event listener's function showTabs and the code runs accordingly.
const tabs = document.getElementsByClassName('tab');
const tabContents = document.getElementsByClassName('tab-content');
const tabsArray = Array.from(tabs);
const tabContentsArray = Array.from(tabContents);
const currentOn = document.querySelector('.on');
const currentShown = document.querySelector('.shown');
const showTabs = (e) => {
currentOn.classList.remove('on');
tabsArray[1].classList.add('on');
currentShown.classList.remove('shown');
tabContentsArray[1].classList.add('shown');
};
tabsArray[1].addEventListener('click', showTabs);
I want to avoid the unnecessary repetition by not not adding 4 almost the same showTabs, showTabs2, showTabs3, showTabs4 functions. Is there any way to do that?
Upvotes: 0
Views: 567
Reputation: 23664
Here's a more dynamic way of thinking about it. Use dataset to help identify which content belongs with which tab
let tabs = document.querySelectorAll('.tab');
let contents = document.querySelectorAll('.content');
tabs.forEach(tab => tab.addEventListener('click', e => {
// e is the event of the click
let thistab = e.target;
let mynum = thistab.dataset.tab
// turn off all on states
tabs.forEach(t => t.classList.remove('active'))
contents.forEach(t => t.classList.remove('active'))
// activate clicked stuff
thistab.classList.add('active');
document.querySelector(`.content[data-target="${mynum}"]`).classList.add('active')
}))
.content {
display: none;
}
.content.active {
display: block;
}
.tab.active {
background: #000;
color: #fff;
}
<div class='tabs'>
<button class='tab' data-tab="1">tab 1</button>
<button class='tab' data-tab="2">tab 2</button>
</div>
<div class='contents'>
<div class='content' data-target='1'>Content for tab 1</div>
<div class='content' data-target='2'>Content for tab 2</div>
</div>
Upvotes: 1