I have a standard ul-based CSS navigation menu. I'm trying to use Jquery to toggle the active menu css class name. However, I'm encountering two issues:
- The window.location.href never equals any of my anchor hrefs. I switched to pathname, but they still do not match each other. Even though in the debugger they appear to.
- I cannot seem to get the li from it's anchor.prev. I need to change the class name on the li.
Here's the html:
<div id="left-content">
<ul>
<li class="separator">Main
<ul>
<li class="active link"><a href="/main1" onclick="toggle_active_menu();">Main 1</a></li>
<li class="link"><a href="/main2" onclick="toggle_active_menu();">Main 2</a></li>
<li class="link"><a href="/main3" onclick="toggle_active_menu();">Main 3</a></li>
</ul>
</li>
<li class="separator">Tools
<ul>
<li class="link"><a href="/tools1" onclick="toggle_active_menu();">Tools 1</a></li>
</ul>
</li>
</ul>
</div>
When an anchor is clicked, it's corresponding li should have "active link" as the class name. And all other li's should be reset to just "link" as the class name.
Here's the Jquery javascript:
function toggle_active_menu() {
$('#left-content a').each(function() {
/*var isActive = $(this).attr('href') == window.location.href;*/
var active = this.pathname == window.location.pathname;
var prev = this.prev();
alert("active: " + active + "\nthis.pathname: " + this.pathname + "\nwindow.location.pathname: " + window.location.pathname + "\nprev: " + prev);
prev.toggleClass('active', active);
});
}
I put the alert in there to help debug. As I mentioned, the clicked anchor's href (or pathname) never matched the window's location href (or pathname). And prev is always undefined instead of being the li of the anchor.
Eventual Answer
After testing the various answers, I fould that I had to remove the onclick calls and call the toggle_active_menu function in the document ready function instead. The window location was not being updated before onclick was being called. Also, I did not use toggleClass so that I could preserve the order of the class names.
function toggle_active_menu() {
$('#left-content ul li ul li a').each(function() {
var pathname = window.location.pathname == '/' ? '/main1' : window.location.pathname;
var active = pathname.indexOf(this.pathname) != -1;
if (active) {
$(this).parent().attr('class', 'active link');
} else {
$(this).parent().attr('class', 'link');
}
});
}