Mikołaj Marciniak Mikołaj Marciniak - 5 years ago 102
Javascript Question

How do I make my navigation item inactive again?

I have a problem with my navigation bar. I am trying to make a functionality where when I click on one navigation item, it expands its children. This works perfectly. When I click on another navigation item, it collapses the previous item and expands the current one. This works perfectly, too. I have recently added a new functionality, where I want the current navigation item to keep its hovered look, making it appear active, if you guys get what i mean.

All I could come up with is this code, which indeed does some of what I want, but it doesnt make the navigation item inactive again after clicking the current navigation item, only when I click a new one. If any of this is unclear, I will provide a link.

$(function(){
$(".main-nav").on("click",function(){
$(this).siblings().find(".inner-nav").hide(); //collapse siblings
$(this).siblings().find('a').attr('id', ''); //make siblings inactive

$(this).find(".inner-nav").toggle(); //expand current item
$(this).find("a").attr('id','nav-active'); //make current item active
$(this).find("ul").find("a").attr('id',''); //remove the nav-active ID from the current items children, as it also will appear as active, which is not the desired functionality
});
});

Answer Source

try this :

$(function(){
    $(".main-nav").on("click",function(){
        $(this).siblings().find(".inner-nav").hide();
        $(this).siblings().find('a').attr('id', '');

        $(this).find(".inner-nav").toggle();
        //$(this).find("a").attr('id','nav-active');
    if ($(this).find("a").attr('id') == 'nav-active') {
        $(this).find("a").attr('id','');
    } else {
        $(this).find("a").attr('id','nav-active');
    }
        $(this).find("ul").find("a").attr('id','');
    });
});

I added just simple verification :

if ($(this).find("a").attr('id') == 'nav-active') {
    $(this).find("a").attr('id','');
} else {
    $(this).find("a").attr('id','nav-active');
}

fiddle

Hope, i understand you right .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download