简体   繁体   中英

How do I add 'active' class to the clicked nav link in javascript?

I have a bootstrap navbar and I am trying to use javascript to change which nav link has the active click based on which navlink was clicked. The problem I am having is that when the user clicks a nav link the javscript works fine, but then when the browser navigates to the corresponding page the changes that the javascript made to the HTML is lost.

CODE:

 document.querySelectorAll(".nav-item").forEach((link) => { link.addEventListener("click", highlightActive, false); }); function highlightActive(e) { document.querySelector(".active").classList.remove("active"); e.target.classList.add("active"); console.log(`Link clicked: ${e.target}`); }
 <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/">LCSRanker</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav nav-pills"> <li class="nav-item active"> <a class="nav-link" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/create/predictions">Create</a> </li> <li class="nav-item"> <a class="nav-link" href="/show/standings">Standings</a> </li> </ul> </div> </nav>

Add the active class to the correct nav item in each html file.

Edit: Since the user commented that he's using EJS and not plain html files, the previous answer is not valid.

You can check the URL when the page loads and add the active class accordingly

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