Question

I'm using a 10-item unordered list as a navigation bar. Using SSI, I put the header and navigation bar into every file. I'd like a way to add class="active" to the ruleset of the currently active page (the current page's corresponding <li> will have a different style).

Including the file in every page means that, in the included file, none of the items can have the active class.

Is there a way to do this in just a few lines of code? (using jQuery/JS)

My other option is to match the last part of the URL to part of the href of the anchor within each list item.

Solution: (courtesy of RomanGorbatko)

var tab = window.location.pathname.split("/");
tab = tab[tab.length - 1];  // This probably is not efficient - suggestions?
if (tab != "") $("#nav a#" + tab).addClass("active");
Was it helpful?

Solution 2

For example. You hame some pages:

And you menu has a next form:

<ul>
    <li class="index">index</li>
    <li class="faq">faq</li>
    <li class="forum">forum</li>
</ul>

Now you check the url of your page.

var index = window.location.pathname.split('/')[1];
$('ul.li').removeClass('active');
$('li.' + index).addClass('active');

Profit!

OTHER TIPS

First detect the page name

var index = document.location.href.lastIndexOf("/") + 1;
var page = document.location.href.substring(index,document.location.href.length);

Than find the li with same name and add class active to it considering the navbar has class navbar in the ul.

$('ul.navbar li').each(function() {
    $(this).removeClass('active');   
    if($.trim($(this).text()) == page) {
        $(this).addClass('active');
    } 
});

This will fulfill your requirement. NOTE: I have assumed li name same as page name

You can first look at the url to detect the page name, then you can match the page name to classes you define on your LIs.

if(document.location.href.indexOf('index')>-1) {
      $('li.index').addClass('active')
}

You can also do this with the page title instead if you wish, instead of the url.

Another trick is to add a class to the BODY tag, per page, and let CSS do the work:

body.index li.index {
    background-color:#FF0000
}

body.aboutus li.aboutus {
  .... whatever
}

Here is a link to a jquery/javascript free solution

http://www.webtrainingcentre.com/server-side-includes/tutorials/create-active-links-using-common-include/

I am sure this will help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top