0

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');
    });
Nick Hats
  • 21
  • 2
  • Does this answer your question? [How can I select an element with multiple classes in jQuery?](https://stackoverflow.com/questions/1041344/how-can-i-select-an-element-with-multiple-classes-in-jquery) – Iain Shelvington Dec 21 '21 at 20:59
  • Not exactly. My website, with the above code, only highlights the about section and does not change when you click on to other sections. I am not sure how to fix this with the JS code. – Nick Hats Dec 21 '21 at 23:34

1 Answers1

1
$(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>
Monika Virmani
  • 431
  • 2
  • 10