Critical Developers

Programmers Knowledge Base

Set active or current tab in sites menu in ASP.Net using jQuery

Mostly we keep our sites menu in masterpage to take the advantage of masterpage(i.e DRY principle). And if we place our global navigation in masterpage it becomes difficult to highlight or indicate the current/active menu.

Here is very simple trick.

Ok so, Lets assume the site menu is htmlized as shown below :-

<ul>
<li id="home"><a href="Default.aspx">Home</a></li>
<li id="categories"><a href="Categories.aspx">Categories</a></li>
</ul>

The trick is very simple, just use a <span> tag on each and every .aspx page with the menu id as its text as shown below.

On Default.aspx <span id="activemenu">home</span>

On Categories.aspx<span id="activemenu">categories</span>

And finally in document.ready block call your setactivetab function as shown here:-

function SetActiveTab() {    
    if ($('#activemenu').length > 0) {
        var tabID = "#" + $("#activemenu").text();
        $(tabID).addClass("current");
    }
}

$(document).ready(function(){
SetActiveTab();
});

Thats it.

Loading