I have a menu and I need to highlight the menu item that loaded the current page. I tried to set server-side the id of the body to something unique and pertaining to the current page being loaded. Surprisingly, I could not get the page file name (or some other unique Id) but only the page title which wasn’t good enough.
The HTML (in a Master page):
<div id="menu"> <ul> <li id="regions"> <asp:HyperLink ID="hlRegions" runat="server" CssClass="menu-item" NavigateUrl="~/Regions.aspx">Regions</asp:HyperLink> </li> <li id="municipalities"> <asp:HyperLink ID="hlMunicipalities" runat="server" CssClass="menu-item" NavigateUrl="~/Municipalities.aspx">Municipalities</asp:HyperLink> </li>
</ul>
</div>
The Javascript:
<script type="text/javascript" > function getPageName() { var loc = document.location.href; return loc.substring(loc.lastIndexOf('/') + 1, loc.indexOf('.')).toLowerCase(); } jQuery(document).ready(function($) { var pageName = getPageName(); log("pageName:", this, pageName); $('#menu li').removeClass("selected-menu"); $('#menu ul #' + pageName).addClass("selected-menu"); }); </script>
Each time the page loads, the “selected-menu” class is removed from all li items under #menu. Then, the “selected-menu” class is added to the li item that has the id equal to the page being loaded.