I have a set of nested unordered lists that represents page navigation. The list looks like this:
<ul class="nav">
<li><a href="/about/">About</a></li>
<li><a href="/Programs/">Programs</a>
<ul>
<li><a href="/Programs/certificateprograms/">Certificate Programs</a></li>
</ul>
<li><a href="/Documents/">Documents</a></li>
<li><a href="/Video/">Video</a></li>
</ul>
I use jQuery to match the current url with the url on the anchor tag within each list item, to set a selected class on the list item:
var $currentURL = window.location.pathname;
//ensure file extension
if($currentURL.indexOf(".aspx") > -1) {
var $url = $currentURL;
}
else
{
var $url = $currentURL.substring(0,$currentURL.lastIndexOf("/")) + "/index.aspx";
}
$('.nav').find('a').filter(function(){
var href = $(this).attr('href');
return href!='/' && href!='#' && href.indexOf($url)==0;
}).parent().addClass('selected');
That works fine if there is an exact match, but sometimes the current page is deeper in the tree, and is not even displayed in the left navigation. In these cases we want walk up the tree from the current url, and set the selected class on the first match we find. So if they are on “/Programs/certificateprograms/level3/level4.aspx” we want to set the selected class on the list item containing “/Programs/certificateprograms/”.
I’m looking for the best way to accomplish this in jQuery. It seems like I should be able to recursively call a function, passing in the current url, and truncating to the lastindex of “/” each time. Does anyone have an idea on how to accomplish this?
If I understand correctly, when the current page is deeper than any of the available nav items, the current url still has the same starting pattern. So, you shouldn’t need recursion. You just need to match that the current url “starts with” the nav item.
Maybe something like this: