简体   繁体   中英

How To Set/Keep 'active' class on link or li when redirect to another page?

In my View i have navigation but problem is when i click on link and redirect me to that page it lose active class and it again become the home to active. Can anyone please help me or point me in the right direction!
Thanks in advance.

View:

<!-- Side Navbar -->
  <nav class="side-navbar shrinked">

      <!-- Sidebar Navidation Menus-->
      <ul class="list-unstyled">
          <li class="active"><a href="/User/Home"> <i class="icon-home"></i>Home </a></li>
          <li><a href="/User/AddEmployee"> <i class=" icon-grid"></i>EMP </a></li>
          <li><a href="/User/AddUser"> <i class="fa fa-bar-chart"></i>User </a></li>
      </ul>

  </nav>

JavaScript:

<script>
    $(function () {

        $('nav.side-navbar ul li a').on('click', function () {
            $(this).parent().addClass('active').siblings().removeClass('active');
        });


    });
</script>

When you load a new page all the code in current page is gone and all the scripts you have will run again on new page.

You need to compare the page's url to the links urls on page load.

Try the following:

$(function() {
  $('nav.side-navbar ul li a').each(function() {
    var isActive = this.pathname === location.pathname;
    $(this).parent().toggleClass('active', isActive);
  });
});

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