I am trying to make a navigation menu I did all the HTML and CSS when come to javascript I am struck in the middle I am able to add a class to the
HTML
CSS
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
*::before, *::after {
box-sizing: border-box;
}
.container {
width: 100%;
max-width: 1024px;
display: block;
margin: 30px auto;
}
ul {
list-style: none;
}
a {
text-decoration: none;
}
.nav {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}
.nav__item {
padding: 1rem;
}
.nav__link {
display: block;
padding: .3125rem 1.5rem;
text-transform: uppercase;
}
.nav__link.active {
border: 1px solid #ff4b4c;
color: #ff4b4c;
}
JS
document.addEventListener('DOMContentLoaded', function() {
const selector = '.nav__link';
const elems = Array.from(document.querySelectorAll(selector));
const navigation = document.querySelector('nav');
function makeActive(evt) {
const target = evt.target;
if (!target || !target.matches(selector)) {
return;
}
elems.forEach(elem => elem.classList.remove('active'));
evt.target.classList.add('active');
};
navigation.addEventListener('mousedown', makeActive);
});
BTW: A great solution is here: https://gomakethings.com/getting-all-sibling-elements-when-a-link-or-button-is-clicked-with-vanilla-js/