I'm new to Javascript and I'm having problem with the tab links set on my webpage.
The links cycle trough and display the appropriate content, however, when it comes to adding the styling of the active button, on loading the page the underline shows correctly and clicking elsewhere keeps it in place, but if I click on the other links and then click elsewhere the styling disappear.
The full code is here https://codepen.io/Rei89/pen/VwBrJEr
this is the piece I'm having trouble with:
const tabsContainer = document.getElementById("links");
const tabs = tabsContainer.getElementsByClassName("tablinks");
for (let i = 0; i < tabs.length; i ) {
tabs[i].addEventListener("click", () => {
let current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className = " active";
});
};
CodePudding user response:
You can add and remove classes using javascript like this. Before adding 'active' class, remove that from all 'tablinks'.
const tabsContainer = document.getElementById("links");
const tabs = tabsContainer.getElementsByClassName("tablinks");
// Loop through the buttons and add the active class to the current/clicked button
for (let i = 0; i < tabs.length; i ) {
tabs[i].addEventListener("click", () => {
removeClasses();
tabs[i].classList.add("active");
});
};
var els = document.querySelectorAll('.tablinks')
function removeClasses() {
for (var i = 0; i < els.length; i ) {
els[i].classList.remove('active')
}
}
CodePudding user response:
You can use other methods such as remove and add :D
const tabsContainer = document.getElementById("links");
const tabs = tabsContainer.getElementsByClassName("tablinks");
for (let i = 0; i < tabs.length; i ) {
tabs[i].addEventListener("click", () => {
let current = document.getElementsByClassName("active")[0];
current.classList.remove("active");
tabs[i].classList.add("active");
});
};