I am just trying to retrofit an active state into a static html menu. The menu has the following structure: -
<div id="navbar">
ul id="MenuBar1" class="MenuBarHorizontal">
<li><a href="index.htm">Home</a></li>
<li><a href="about.htm">About Us</a></li>
<li><a href="products.htm">Products</a>
<ul>
<li><a href="product-grp1">Product Groups 1</a>
<ul>
<li><a href="product1.htm">Product 1</a>
<li><a href="product2.htm">Product 2</a>
<li><a href="product3.htm">Product 3</a>
</ul>
</li>
</ul>
</li>
</ul>
</div>
You can see that this is a 3 level menu system which actually displays as a mega menu.
What I would like to do is, based on the URL of the page you are on, add an active state to the top level menu. This active state would need to show whether you are on a second or third level page. I need to do this based on the page url rather than a click as the site does have quite a lot of links directly from Google to specific pages, so I will need to show where those sit too.
Note that the file structure is flat so each url is http://www.thesite.com/about.htm etc.
I've been trying to sort this out from previous questions, but just can't get it to work. I'm guessing that's because of the depth of the menu, but would really appreciate any guidance anyone can give me.
THANKS for all your help. This really put me on the right track. In the end I used the following: -
/* The following adds active to the next level up of the url */
$('#MenuBar1 li a').each(function() {
if(filename == $(this).attr('href')) {
$(this).addClass('active');
}
});
/* The following line looks for the .active class, then the parent of it with the #navbar ul.... structure, then adds the active class to that one only */
$('.active').parents('#navbar ul.MenuBarHorizontal li').addClass('active-top');
$('#navbar ul.MenuBarHorizontal>li').addClass('menu-top');
What this does is used jQuery to add an .active class to the particular link, then adds an .active-top to the parents (all of them unfortunately as I couldn't work out how to target just the level I wanted). The last line adds a .menu-top class to the top level of the menu.
This structure lets me target just the top level of the menu without the formatting flowing down the DOM to other child selectors. It probably isn't the most elegant solution, but it does work.
Thanks again to everyone who gave me advice.