I feel like this should be an easy task, but I am having problems. I have a drop down menu that is wrapped in an unordered list (generated by an asp.net menu control) and I am trying to add extra highlighting to a selected link’s parent link via jquery. Here is the generated HTML:
<div id="MainMenu" class="mainMenuControl">
<ul class="level1 static" role="menubar">
<li class="static" role="menuitem"><a class="level1 static selected" href="/default.aspx">Home</a>
</li>
<li class="has-popup static" aria-haspopup="MainMenu:submenu:3" role="menuitem"><a
class="level2 static" href="/store/prodcut.aspx">Product 1</a>
<ul id="MainMenu:submenu:3" class="level3 dynamic">
<li class="dynamic" role="menuitem"><a class="level3 dynamic" href="/store/product/category1.aspx">
Category 1</a> </li>
<li class="dynamic" role="menuitem"><a class="level3 dynamic" href="/store/product/category2.aspx">
Category 2</a> </li>
</ul>
</li>
<li class="has-popup static" aria-haspopup="MainMenu:submenu:10" role="menuitem"><a
class="level2 static" href="/store/paymentoptions.aspx">Ministries</a>
<ul id="MainMenu:submenu:10" class="level3 dynamic">
<li class="dynamic" role="menuitem"><a class="level3 dynamic" href="/store/paymentoptions/option1.aspx">
Option 1</a> </li>
<li class="dynamic" role="menuitem"><a class="level3 dynamic" href="/store/paymentoptions/option2.aspx">
Option 2</a> </li>
</ul>
</li>
</ul>
</div>
So, whatever page the current user is on, the corresponding menu link will have the class ‘selected.’ But, if they are on a sub page of one of the main menu choices, I would like the link in the drop down menu as well as it’s parent link to both have the ‘selected’ class.
I was attempting to add classes to the links based on parent/child url paths but I’m running into problems because I am using url rewriting in asp.net so that any trailing slashes, default documents (index.html, default.aspx) or url endings (.html, .aspx, etc) are removed.
I tried this, but, as I said, I can’t get it to work:
$('.mainMenuControl ul a').each(function () {
if ($(this).attr('href') == window.location.pathname) {
$(this).addClass('selected');
if ($(this).parent('li').parents('.mainMenuControl ul.level1 li').length) {
$(this).parent('li').parents('.mainMenuControl ul.level1 li').find('a.static').addClass('selected');
}
}
});
Any suggestions would be appreciated, thanks!
Why do it in jQuery. If your using a master page you can create a label called lblMenu.
So like…
Then create a class that accepts overides of the names of the items you want selected.
Build up the HTML for your menu in this class and the options passed to it will have selected against them.
On your content page_load events put something like..