简体   繁体   中英

Current Active Link with JS ES6

Im currently trying to fix up my Nav bar so that the current link will have a class of 'active' applied to it.

I have managed to set up the toggle but I'm really struggling to find resources on how to clear the class off the other links.

Everything on here seems to primarily be focused on JQuery which I am intentionally trying to avoid.

Here is my code:

<div class="navbar">
        <a href="#" class="toggle" id="nav-hamburger">
            <i class="fas fa-bars"></i>
            <a href="#" class="brand">Appeal Digital</a>
        </a>
        <div class="links">
                <a href="#" class="link active">Home</a>
                <a href="#" class="link">Who are we?</a>
                <a href="#" class="link">Meet the Team</a>
                <a href="#" class="link">Contact Us</a>
        </div> 
    </div>


const toggleBtn = document.querySelector('#nav-hamburger');
toggleBtn.addEventListener('click', (el) => {

    //TOGGLE NAV BUTTON
    const links = document.querySelector('.links');
    links.classList.toggle('links-show');
});

const links = document.getElementsByClassName('link');

for(let el of links) {

    el.addEventListener('click', (e) => {
        el.classList.remove('active');
        el.classList.toggle('active');    

    });
}

I would remove all .active classes if you click on a menu link and set the .active class for clicked link.

 const links = document.querySelectorAll('.links > a'); const changeActive = (e) => { [...links].forEach(link => link.classList.remove('active')); e.target.classList.add('active'); } [...links].forEach(e => e.addEventListener('click', changeActive));
 .active { font-weight: bold; }
 <div class="navbar"> <a href="#" class="toggle" id="nav-hamburger"> <i class="fas fa-bars"></i> <a href="#" class="brand">Appeal Digital</a> </a> <div class="links"> <a href="#" class="link active">Home</a> <a href="#" class="link">Who are we?</a> <a href="#" class="link">Meet the Team</a> <a href="#" class="link">Contact Us</a> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM