RoyBar RoyBar - 1 month ago 11
jQuery Question

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 code (it's rendered by PHP foreach loop so it's not hard coded as it looks)

$(document).ready(function() {
var selector = '.sidebar-nav li';
$(selector).on('click', function() {
$(selector).removeClass('active');
$(this).addClass('active');
});
});


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<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>

Answer

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).addClass('active');
        }
     });

I hope it helps