Skip to content

Current Page Aware Menu Class With jQuery

by on April 4, 2012

The following uses a matrix of case insensitive menu item text and page urls to highlight the menu item matching the current page. This is great for a small menu of items, but does not work with exact matches (so Help and Code Help would both be highlighted menu items.

The HTML

<div class="toptabs">

<div class="toptabsinner">

<a href="/pages/myaccount.aspx">My Account</a>

<a href="/pages/myservices.aspx">My Services</a>

<a href="/pages/help.aspx">Help</a>

</div>

</div>

The Javascript/jQuery Code

//create case insensitive :contains selector
$.expr[":"].containsNoCase = function(el, i, m) {    var search = m[3];    if (!search) return false;    return eval("/" + search + "/i").test($(el).text());};   
               

                //if url contains tabname add current tab class
                var isPage = window.location.pathname.toLowerCase();
                var PageIndexes = [
                                ["/myaccount.aspx","my Account"],
                                ["/Myservices.aspx","my services"],
                                ["/help.aspx","help"]
                                ];
                for (i=0;i<PageIndexes.length;i++){
                   if(isPage.indexOf(PageIndexes[i][0].toLowerCase())>-1){
                     $(‘.toptabsinner > a:containsNoCase("’+PageIndexes[i][1]+’")’).addClass(‘currentTopTab’);
                    }
                };

Advertisements
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: