I want to remove the class active
to the elements that were not clicked, I am adding the class active
when each element is clicked.
const tabs = document.querySelectorAll('.tab')
const slider = document.querySelector('.slider')
tabs.forEach((tab, i) => {
tab.addEventListener('click', () => {
let styles = `left: ${tab.offsetLeft}px;
width: ${tab.offsetWidth}px;`;
slider.style.cssText = styles
tab.classList.add('active');
})
})
body {
display: flex;
justify-content: center;
}
.tabs-container {
position: relative;
display: flex;
margin-top: 55px;
height: 35px
}
.tab {
margin: 0px 20px;
text-transform: capitalize;
font-weight: bold;
font-family: arial;
font-size: .9em;
cursor: pointer;
}
.tab.active {
color: red;
}
.slider {
background-color: red;
height: 5px;
width: 100px;
position: absolute;
left: 0;
bottom: 0;
transition: 300ms left ease-in-out, 300ms width ease-in-out
}
<div class="tabs-container">
<div class="tab active" data-tab="general">general</div>
<div class="tab" data-tab="business">business</div>
<div class="tab" data-tab="technology">technology</div>
<div class="tab" data-tab="health">health</div>
<div class="slider"></div>
</div>
What you are missing is removing the class
active
before assigning it to the new "clicked" element.Example: