I have this menu in _Layout.cshtml :
<td class="MenuStructure">
<ul id="menu">
<li>@Html.ActionLink("First Page", "Page1Action", "Main")</li>
<li>@Html.ActionLink("Second Page", "Page2Action", "Main")</li>
<li>@Html.ActionLink("Third Page", "Page3Action", "Second")</li>
</ul>
</td>
When one of the action links is clicked, I want to set the class of the <li> which contains it to “selected” and the class of the other <li> elements to “”.
This works :
<script type="text/javascript">
$(document).ready(function () {
var selMenu = '@ViewBag.SelectedMenu';
if (selMenu == "page1") {
$("#page1").attr('class', 'selected');
$("#page2").attr('class', '');
$("#page3").attr('class', '');
}
if (selMenu == "page2") {
$("#page1").attr('class', '');
$("#page2").attr('class', 'selected');
$("#page3").attr('class', '');
}
});
</script>
but it is awfully ugly. Can someone show me a more elegant way to do this?
If you add a click event handler to the group of
aelements, you can easily add the class to the clicked element’sliand remove it for all siblings, regardless of how many there are. This removes the need for the if statements and theattrupdate for eachli.Here’s a sample:
http://jsfiddle.net/JjBgm/4/
markup:
jQuery:
You’d have to obviously modify this approach to your needs with MVC, but the concept should work.
EDIT: Because you mentioned there is a round-trip to the server involved the above may not work well. In that case you could construct the clientside id based on the selected menu and control the class from there.
This is assuming
#page1,#page2, etc. refer to the<li>elements without seeing your resulting markup after server processing.If
#page1refers to the<a>tag, then your statement would be:Untested of course. Main point is dynamically construct your selector, then use sibling and parent selectors as needed to clear the class. It’s much cleaner.