Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to li after page is loaded

I have a nav bar with links that are loaded from a database by a foreach loop, the nav bar is static so only the content in changing. I want to add an 'Active' class to the link when the page is loaded an active.

I've tried to simply add class when an li element is clicked, but the class disappears when the page is reloading.

Here is my HTML (it's rendered by PHP foreach loop so it's not hard coded as it looks)

<div class="sidebar-menu">
  <ul class="sidebar-nav">
    <li class="icon_links">
      <a href="/home" class="links">
        <div class="icon">
          <i class="fa fa-tasks" aria-hidden="true"></i>
        </div>
        <div class="title">Dashboard</div>
      </a>
    </li>
    <li class="icon_links">
      <a href="/messaging" class="links">
        <div class="icon">
          <i class="fa fa-comments" aria-hidden="true"></i>
        </div>
        <div class="title">Messaging</div>
      </a>
    </li>
  </ul>
</div>

JavaScript

$(document).ready(function() {
  var selector = '.sidebar-nav li';
  $(selector).on('click', function() {
    $(selector).removeClass('active');
    $(this).addClass('active');
  });
});
like image 393
RoyBar Avatar asked Dec 06 '22 16:12

RoyBar


1 Answers

You need to do something like this:

    var selector = '.sidebar-nav li';
    var url = window.location.href;
    var target = url.split('/');
     $(selector).each(function(){
        if($(this).find('a').attr('href')===('/'+target[target.length-1])){
          $(selector).removeClass('active');
          $(this).removeClass('active').addClass('active');
        }
     });

I hope it helps

like image 186
Abhay Maurya Avatar answered Dec 08 '22 06:12

Abhay Maurya