Ernest Mercado
Ernest Mercado

Reputation: 3

Highlight Current Page Link With Submenus Using Javascript

I am trying to highlight the current page link, like this... Image Here

Thanks to the others before me who have asked this, I have been able to do so properly.

But, My Navigation Bar has a sub menu.

I am trying to highlight the parent of the sub menu whenever I am in it. But, whenever I am from a parent menu (example the "MAIN") and went to a sub menu from a different parent (example the "TRANSFEREES") this happens...Image Here

here is the html for the menu...

<ul id = "nav">
<li><a href = "Index.html">MAIN</a></li>
<li><a href = "About.html">ABOUT US</a></li>
<li><a href = "Admission.html">ADMISSION</a>
    <ul class = "sub">
        <li><a href = "Freshmen.html">FRESHMEN</a></li>
        <li><a href = "Transfer.html">TRANSFEREES</a></li>
    </ul>
</li>   
</ul>

Here is the Javascript code...

$('ul#nav li a').click(function(){
$(this).closest('ul#nav li').addClass('active').siblings().removeClass('active');       
return false;
});

And the CSS...

ul#nav li.active{
background:#9993a6;}

I have tried looking for a solution for this everywhere, I am a newbie at Javascript so if any of you could help me... I would really appreciate it... Thanks in advance.

Upvotes: 0

Views: 716

Answers (2)

Vi100
Vi100

Reputation: 4203

Try removing the active class for every list item in the list and it's sublists, and then add the active class to the items you want, otherwise you'll have to control too many cases.

This is the code:

$('ul#nav li a').click(function(){
    $('#nav li').removeClass('active');
    $(this).addClass('active');
    var possibleParent = $(this).parents('#nav li');
    if (possibleParent) possibleParent.addClass('active');
});

And here a Codepen demostrating: http://codepen.io/anon/pen/jWORRG

Upvotes: 0

Andres Espinosa
Andres Espinosa

Reputation: 402

The way you are removing active class is wrong, because addClass does not return a jQuery object, so you cannot use siblings() on it.

I also think is better to use parents instead of closest, you should try something like this:

$('ul#nav li a').click(function(){
    var listElement = $(this).parents('ul#nav li');
    listElement.addClass('active');
    listElement.siblings().removeClass('active');
    return false;
});

Upvotes: 1

Related Questions