I have the following code which tries to add a class of selected to a link that matches the url:
var pathname = window.location.pathname;
$(document).ready(function ()
{
$('ul#ui-ajax-tabs li a').each(function()
{
if (pathname.indexOf($(this).attr('href')) == 0)
{
$(this).parents('li').addClass('selected');
}
});
});
1.) So for example if I have a url like /Organisations/Journal and /Organisations/Journal/Edit a link with Organisations and Journal will show as being selected. This is fine!
2.) However sometimes I have urls like: /Organisations and /Organisations/Archived and if I have a link to the Archived then both will be selected BUT I don’t want this to happen because the Organisations like doesn’t have the second part of the url so shouldn’t match.
Can anyone help with getting this working for the second types Without breaking the first type? Also none of this can be hardcoded regex looking for keywords as the urls have lots of different parameters!
Cheers
EXAMPLES:
If the url is /Organisations/ Or /Organisations then a link with /Organisations should be selected. If the URL is /Organisations/Journal/New then a link with /Organisations/Journal or /Organisations/Journal/New would be selected.
BUT if I have a url with /Organisations/Recent and have two links: /Organisations and /Organisations/Recent then only the second should be selected! So the thing to note here is that it must have a third parameter before it should look for bits of the URL more loosly rather than an exact match.
Remember it might not always be Organisations so it can’t be hardcoded into the JS!
Edit: My previous solution was quite over-complicated. Updated answer and fiddle.
The best match is calculated like so:
Assume our pathname is “/foo/bar/baz/x”.
We have two links in question:
This is what happens:
/foo/bar/baz/x (the first link’s url is deleted from the path namepathname.replace($(this).attr('href'), ''))length) of this remainder is 5. this is our “penalty” for the link.if (overlap_penalty < best_distance)). 5 is lower (=better) than 999.this(being the<a href="/foo/bar/">DOM object) for possible later use./foo/bar/baz/x (the second link’s url is deleted from the path name)this(being the<a href="/foo/bar/baz">DOM object) for possible later use.In the end, we just check if we found any matching link and, if so, apply
addClass('selected')to its closest<li>parent.