How to add the class "active" according to the page accessed

0

I have a separate layout in my project, where it is standard for all pages. how to do in the left menu, the active class is activated according to the selected page.

I have the html code:

<div class="sidebar-sticky">
     <ul class="nav flex-column">
           <li class="nav-item active">
                <a class="nav-link" href="~/Alunos/Index/">Alunos</a>
           </li>
           <li class="nav-item">
                <a class="nav-link" href="~/Funcionarios/Index/">Funcionarios</a>
           </li>
      </ul>
</div>

And I tried to make it work with the script

jQuery(function() {
    $("a").click(function() {
        $("a").removeClass("active");
        $(this).addClass("active");
    });
}

But it does not work, any suggestions?

    
asked by anonymous 27.05.2018 / 22:19

1 answer

1

You can make this work easier by using CSS only

.nav-item a:active,a:focus{
  color: #188ae2;
}

But if you're still not satisfied using CSS, you can use JS

$('.nav li').click(function() {
    $(this).siblings('li').removeClass('active');
    $(this).addClass('active');
});

Example with javascript: link

Example with CSS: link

    
27.05.2018 / 23:12