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

Asked

Viewed 3,597 times

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’ve tried to make it work with the script

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

but it doesn’t work, some suggestion?

1 answer

2


You can facilitate this work using CSS only

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

But if you’re not yet satisfied using CSS, you can use JS

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

Example with javascript: https://jsfiddle.net/0w3xfc3y/1/

Example with CSS: https://codepen.io/anon/pen/rvXEWW

Browser other questions tagged

You are not signed in. Login or sign up in order to post.