简体   繁体   中英

I am trying to add an active class to my nav bar items on my website when clicked

I want to add the active class to the navbar item that I click on, on my website. In my JS code, it tells the program what class to look under ("nav-item"). Then it tells my program to remove the active class from the current active class, and then add the active class to the class that was clicked.I'm assuming the logic is correct but I most likely missed syntax. I am new to HTML and JS so any help would be greatly appreciated.

HTML Code:

<ul class="navbar-nav">
                    <li class="nav-item"><a class="nav-link js-scroll-trigger active" href="#about">About</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li>
                </ul>

JS code:

$('.nav-item').on('click', '.nav-link js-scroll-trigger', function () {
        $('.nav-link js-scroll-trigger active').removeClass('active');
        $(this).addClass('active');
    });
$(document).ready(function(){
  $('.nav-link').click(function(){
    $('.nav-link').removeClass("active");
    $(this).addClass("active");
});
});

 $(document).ready(function(){ $('.nav-link').click(function(){ $('.nav-link').removeClass("active"); $(this).addClass("active"); }); });
 .active{ color:yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="navbar-nav"> <li class="nav-item"><a class="nav-link js-scroll-trigger active" href="#about">About</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li> </ul>

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