Highlight the Current Page with jQuery, CSS &  PHP

Here’s a common web development scenario: How do we highlight the current page in a navigation seamlessly and dynamically? The answer is jQuery.

See a Live Demo

My recipe for this common scenario involves a mixture of CSS and JavaScript with a dash of jQuery.

HTML

<ul id="navigation">
    <li><a href="/about/">About</a></li>
    <li><a href="/services/">Services</a></li>
    <li><a href="/blog/">Blog</a></li>
    <li><a class="active" href="/contact/">contact</a></li>
</ul>

JavaScript / jQuery

$(function(){
    $page = jQuery.url.attr("file");
    if(!$page) {
        $page = 'index.html';
    }
    $('#navigation li a').each(function(){
        var $href = $(this).attr('href');
        if ( ($href == $page) || ($href == '') ) {
            $(this).addClass('on');
        } else {
            $(this).removeClass('on');
        }
    });
});

Usage

You’ll need a copy of jQuery, along with a copy of the jQuery URL Parser plugin.

After you include jQuery, and the URL Parser add the JavaScript snippet above to the <head> section of your document.

How it works

What we do here is simple, we grab the current name of the page, for example about.html. Then we check out ul.navigation <ul> to see if any of the anchors contain an href attribute with that value. If any of the links are a match we flag the parent of the anchor with a CSS class. In this case I’ve chosen current to keep things self explanatory.

Notes

In this case I chose to add the “current” class to the <li> rather than to the anchor. Usually I will create a navigation using CSS sprite techniques, and this allows me greater control over the presentation of that element. This can come in handy for rounded corners or tabs.