I have a menu created by a list. I would like to be able to highlight the current menu item.
With this script I'm able to match the last bit of the url (everything after the last /
), but I need the script to match the two previous folders in the url as well. So instead of e.g.index.html
, I'd like to grab /folder1/folder2/index.html
.
$(function () {
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$(".nav li a").each(function () {
//console.log(url);
if ($(this).attr("href") == url) $(this).parent().addClass("active");
});
});
//Markup:
<ul id="nav">
<li><a href="/folder1/folder2/index.html">Home</a></li>
<li><a href="/folder1/folder2/about.html">About</a></li>
<li><a href="/folder1/folder2/contact.html">Contact</a></li>
</ul>
How do I modify the script to match more parts of the url?
this one should work:
$(function () {
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$('[href$="'+url+'"]').parent().addClass("active");
});