Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically apply active class to nav li

I have included a header to my files as in include. In the header is the nav bar.

How do I, using jQuery, apply class="active" to the relevant li.

The only way I could think of doing it is to set a variable on the actual pages, apply an id that is equal to that variable of the relevant page and if function so if they match apply a class to the li.

However, I thought there must be a simpler way of achieving this.

<ul class="nav nav-pills right" id="div">
    <li id="home" class="active">
       <a href="index.php">Home</a>
    </li>
    <li id="search">
       <a href="search.php">Search</a>
    </li>
    <li id="contact">
      <a href="contact.php">Contact</a>
    </li>
</ul>
like image 338
RSM Avatar asked Apr 18 '26 06:04

RSM


2 Answers

An easy way to do this would be to have a script per page:

$('#home').addClass('active'); // for home page

You could try and match the href to the current url:

var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
like image 188
Paul Fleming Avatar answered Apr 19 '26 20:04

Paul Fleming


More compact way:

$(function(){
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    $('a[href="'+ sPage +'"]').parent().addClass('active');
});
like image 20
JohnJohnGa Avatar answered Apr 19 '26 18:04

JohnJohnGa