I make a menu and some section. This website works like vcard so when you clicked to item in menu should be add class show to section and show this section and class active to menu item. So the menu item its simply and works for me but now how to add class show.
HTML
<nav class="nav-desktop">
<div class="nav-items">
<a class="nav-item" href="#about">About</a>
<a class="nav-item" href="#ourteam">Skills</a>
<a class="nav-item" href="#contact">Contact</a>
</div>
</nav>
<section class="about section show" id="about"></section>
<section class="ourteam section" id="ourteam"></section>
<section class="contact section" id="contact"></section>
const allNavItem = document.querySelectorAll('.nav-item')
function removeActiveMenu() {
allNavItem.forEach(item => {
item.classList.remove('active')
})
}
allNavItem.forEach(item => {
item.addEventListener('click', () => {
removeActiveMenu()
item.classList.add('active')
})
})
So now how i can add class 'show' to section ourteam when i click ourteam in menu and remove from section about. How to combine this.
Just remove all active/show state and then add again for suitable element
const sections = document.querySelectorAll('.section');
const navItems = document.querySelectorAll('.nav-item');
navItems.forEach(navItem => {
navItem.addEventListener('click', function(e) {
e.preventDefault();
// remove all active / show state
navItems.forEach(
item => item.classList.remove('active')
);
sections.forEach(
section => section.classList.remove('show')
);
// add active / show state again
this.classList.add('active');
const target = this.getAttribute('href');
document.querySelector(target)?.classList.add('show');
});
});