Hi , This is a long one . But I have a nav bar that slide and I want to make it close after I click on a links that takes me to a section of the page.
so far I had this code that someone actually give it to me
[code]
// Handle close bar
const closeNavbar = () => {
$(‘.nav-links’).removeClass(‘nav-activ’)
}
// Toggle hamburger animation
const toggleHamburgerBtn = () => {
$(“.burger”).toggleClass(‘animation’)
}
// Handle change link
const changeLink = () => {
$(‘.nav-links a’).on(‘click’, () => {
closeNavbar()
toggleHamburgerBtn()
})
}
But I this uses jQuery so I tried to write the same thing in javaScript. And as I am new to coding it took me a while and some variations of the code to make it work. At least kinda make it work.
The code that I managed to make it work with this this on
[code]const closeNav = () => {
const navLinks = document.querySelector(‘.nav-links’);
navLinks.classList.remove(‘nav-active’);
}
const closeBurger = () => {
const burger = document.querySelector(‘.burger’);
burger.classList.remove(‘animation’);
}
const closeSlide = () => {
const links = document.querySelector(‘.nav-links a’);
links.addEventListener(‘click’, () => {
closeNav();
closeBurger();
})
}
closeSlide();
The problem with this on is that only work for the first a tag, no for all . I think I need to an an .forEach I dont exactly know how but I have an idea.
I think it shoud be something along the lines
[code]links.forEatch(a => {
a.addEventListener(‘click’, () => (
closeNav();
closeBurger();
))})
But the main question is why this code doesn’t work ? I tried to reduce the code as much as I could.
[code]const navSlide = () => {
const burger = document.querySelector(‘.burger’);
const navLinks = document.querySelector(‘.nav-links’);
const links = document.querySelector(‘nav-links a’);
burger.addEventListener(‘click’, () => {
navLinks.classList.toggle(‘nav-active’);
burger.classList.toggle(‘animation’);
links.addEventListener(‘click’, () => {
navLinks.classList.remove(‘nav-active’);
burger.classList.remove(‘animation’);
})
});
}
navSlide();
This function is the function that makes the nav slide.