简体   繁体   中英

how to dynamically change active class in navbar using javascript

I'm trying to set the navbar to dynamically change class to 'active' in the current page when the user click on the <li> tag. Where did I go wrong?

 dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a').on('click', function() { $('.nav_w3ls .menu').find('a.active').removeClass('active'); $(this).parent('a').addClass('active'); }); }
 <div class="nav_w3ls ml-lg-5"> <nav> <label for="drop" class="toggle">Menu</label> <input type="checkbox" id="drop" /> <ul class="menu"> <li><a href="index.php" class="active">Home</a></li> <li><a href="about.php">About</a></li> <li><a href="why_us.php">Why Us</a></li> <li><a href="pricing.php">Pricing</a></li> <li><a href="contact.php">Contact</a></li> <li class="nav-right-sty mt-lg-0 mt-sm-4 mt-3"> <a href="pages/login.php" class="reqe-button text-uppercase">Login</a> <a href="pages/register.php" class="reqe-button text-uppercase">Register</a> </li> </ul> </nav> </div>

I expect the navbar to be active for the current page

First you need to get you page name. Then you add the class to the a element that has this page name as href attribute.

$(document).ready(function() {
    $('.nav_w3ls .menu').find('a.active').removeClass('active');

    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    $('.nav_w3ls .menu').find('a[href=' + sPage + ']').addClass('active');
});

 dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a').on('click', function() { $('.nav_w3ls .menu').find('a.active').removeClass('active'); $(this).addClass('active'); }); }
 <div class="nav_w3ls ml-lg-5"> <nav> <label for="drop" class="toggle">Menu</label> <input type="checkbox" id="drop" /> <ul class="menu"> <li><a href="index.php" class="active">Home</a></li> <li><a href="about.php">About</a></li> <li><a href="why_us.php">Why Us</a></li> <li><a href="pricing.php">Pricing</a></li> <li><a href="contact.php">Contact</a></li> <li class="nav-right-sty mt-lg-0 mt-sm-4 mt-3"> <a href="pages/login.php" class="reqe-button text-uppercase">Login</a> <a href="pages/register.php" class="reqe-button text-uppercase">Register</a> </li> </ul> </nav> </div>

Your code worked just fine, the only issue was on the last line. You didn't have to call the "parent method" on the 'this'.
$(this).addClass('active');

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