thanks for taking the time to read this.
I have a JavaScript (jQuery) navigation bar on my main page that is simply "included" on my page. For example, I have index.shtml that "includes" the nav bar, which is "nav_bar.shtml". And this is the same for every other page. Now clearly, with the current setup, there's no way to show the user which menu item is currently selected since the nav_bar.shtml page stays static.
What I'm wanting to do is STILL have just the one nav_bar.shtml file, but be able to, on the individual pages, show the user the current menu item selected on the nav bar (as in a different shade of color, etc.). If nav_bar.shtml stays static, there's not a very clear way to do this. Is there a workaround to this if I don't want to instantiate an entirely new Javascript nav bar on each and every page? Or would each page need its own version of the nav_bar code specific to that page so it knows which item it needs to shade?
One way to do this is to write some code to look in your menu, find the href
s of the links therein, and compare them to the current window.location.pathname
. If you have nice clean URLs this isn't too hard. If you have long, complex URLs, it may not be workable.
So, here's the general idea:
$(document).ready( function(){
var thispage = location.pathname.substring(1);
$('#menu li a[href~="' + thispage + '"]') // ~= is contains. Tweak as needed.
.addClass('active');
});
Assuming your menu looks something like this:
<ul id="menu">
<li><a href="page1.html">This</a></li>
<li><a href="page2.html">That</a></li>
<li><a href="page3.html">The Other</a></li>
</ul>
And of course:
li.active {
background-color: yellow;
}