I have the following menu in my masterpage:
<ul id="menu" class="lavaLampBottomStyle">
<li>
<%= Html.ActionLink("Employees", "Index", "Employees")%></li>
<li>
<%= Html.ActionLink("Customer", "Details", "Account")%></li>
</ul>
I need a way to set the css class of the current active li to “current”.
My first guess it to do this with the assistance of javascript.
I would include something like this in the masterpage:
$("#menu li a").each(){
if($(this).attr("href") == '<%= *GET CURRENT PAGE* %>'){
$(this).parent("li").addClass("current");
}
}
Is this a good approach?
If it is, how can I get the current URL part like in the href?
If it isn’t, what’s your suggestion? 🙂
FYI, the generated html I’m after:
<ul id="menu" class="lavaLampBottomStyle">
<li>
<a href="/KszEmployees/Index">Employees</a></li>
<li>
<a class="current" href="/">Customer</a></li>
</ul>
That’s probably the least intensive way of doing it. If you can count on the users to have javascript enabled, I see nothing wrong with this, and have done it myself on occasion.
Request.Url is the object you are interested in to get the current page on the server side. The suggestion to use window.location.href by tvanfosson isn’t bad either if you want to keep it entirely clientside.
The advantage of using serverside, is that Request.Url has easily accessible parts of the url, such as Request.Url.Host, etc to help with your link-munging needs.