View Full Version : navigation menu both submenu and parent class active

01-18-2012, 10:35 PM
I have a navigation menu with one level of submenu, and the code that I have allowes me when I click on the parent, the submenu opens (and remains open). When I click on a subitem, the page travels to that url, but the code that I have compares the document.location to the href of the menu items and display the submenu.
Now the active page is hightlighted, but the parent isn't (if the active page is a submenu).
So what I want is that when a subitem is active, also it's parent should be active, for example:


In this case when sub_item_2 is active, also main_item_2 should be.

I have tried to use parent(), parents(), but none worked the right way, or at least for me the way I want it.

So here is the code I use:

$('#topnav ul li ul.submenu li a').click(function(e){
if ($(this).attr('class') != 'active'){
$('#topnav ul li a').removeClass('active');
return this.href === document.location.href;
$("ul.submenu > li > a").each(function () {
var currentURL = decodeURIComponent(document.location.href);
var thisURL = $(this).attr("href");
if (currentURL.indexOf(thisURL) != -1) {
$(this).parents("ul.submenu").css('display', 'block');
$('#topnav > ul > li > a').each(function(){
var currURL = decodeURIComponent(document.location.href);
var myHref= $(this).attr('href');
if (currURL.match(myHref)) {
//$('a', $('.active').parents("li:last")).addClass('active');
$(this).parent().find("ul.submenu").css('display', 'block');

The middle group code is for the subitem, so the code to make the parent also active should be there I think.

When I add the following line to the middle group (after the $(this).parents part):

$(this).parents("#topnav ul li").addClass('parent');

I am able to make the background of the top parent different, because the parent class changes the background color, but should also change the color of the menu text (parent), but .... not only the most top li has the parent class, also the li which is around the active subitem, which should only be the parent.

Please help.