Set active state of navigation dynamically

If your working in PHP or a CMS like WordPress or Expression engine and your creating a custom theme/solution, you will surely run into the need to create a dynamic navigation with active states. The problem will be that your entire navigation will be in your header.php file, so you cannot hard code your active nav class.

The PHP Way:

Lets use the following navigation code to do this:

<nav id="main-menu" class="padbot">
<ul id="ce">
    <li class="cemenu"><a href="/about">About</a></li>
    <li class="cemenu"><a href="/consulting">Consulting</a></li>
    <li class="cemenu"><a href="/intelligence">Intelligence</a></li>
    <li class="cemenu"><a href="/academy">Academy</a></li>        
    <li class="cemenu"><a href="/blog">Blog</a></li>
    <li class="cemenu"><a href="/contact">Contact</a></li>
 </ul>

Here is an example of a <li> with an active css class I made:

<li class="cemenu active"><a href="<?php echo $base_url;?>/about">About</a></li>

Solution:

If you’re not using URL rewriting (example: you didn’t change your permalinks) this is your solution:

<?php echo ($_SERVER['PHP_SELF'] == '/about' ? ' active' : '');?>"><a href="/about">About</a></li>

If you did use URL rewriting, you’ll want to change:

$_SERVER[‘PHP_SELF’]

to

$_SERVER[‘REQUEST_URI’]

The Javascript Way:

I preferred to use the above method when doing this because I was in WordPress and figured I would stick with PHP. However, here is your Javascript solution to this.

This will add the active class to the <a> which contains the page from the url.

$(function(){
   var url = window.location.href;
   var page = url.substr(url.lastIndexOf('/')+1);
   $('.cemenu a[href*="'+page+'"]').addClass('active');
});