navigation menu both submenu and parent class active
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:
main_item_1
main_item_2
--sub_item_1
--sub_item_2
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:
Code:
$('#topnav ul li ul.submenu li a').click(function(e){
if ($(this).attr('class') != 'active'){
$('#topnav ul li a').removeClass('active');
$(this).addClass('active');
}
});
$('a').filter(function(){
return this.href === document.location.href;
}).addClass('active')
$("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)) {
$(this).addClass('active');
//$('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.
Bookmarks