jQuery - Marking Current Link Active

Have you ever wanted to have a link show as "Active" when a users is on that link? If you have a navigation at the top of your site and you want to visually indicate that the visitor is on that link, then you would usually add and "active" class to that link and style it appropriately.

This little snippet of code will do that.

$(document).ready(function(){
    var path = location.pathname.substring(1);
    if ( path ) {
        $('.header a[href$="' + path + '"]').addClass('active');
    }
});

location.pathname.substring(1); will return the url that you are on, subtract the hostname name.
a[href$="' + path + '"] looks for all anchor tags inside of the header block whose end match the path.

This is pure genius.

References:
http://docs.jquery.com/Tutorials:Auto-Selecting_Navigation

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <drupal5>, <drupal6>, <javascript>, <php>, <sql>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options