0

I have the code below to add a .active class to a link if the href is equal to the url. It is working for the menu items but for the submenu items its not working properly. For example if the link with text "Edit" is clicked i want to add the .active class to the main link with text "Item 1". But its not working tihs part, do you know how to achieve that?

html

<nav id="nav">
    <ul class="">
        <li class="active"><a href="url">Item 0</a></li>
        <li>
            <a href="#edit" data-toggle="collapse" aria-expanded="false">
               Item 1
            </a>
            <ul class="collapse" id="edit">
                <li><a href="/create">Create</a></li>
                <li><a href="/edit">Edit</a></li>
            </ul>
        </li>
        <li><a href="/posts">Item 2</a></li>
    </ul>
</nav>

js

$("#nav a").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
  • 1
    Try adding `console.log(this.href, window.location.href)` and see how they compare. – Barmar Jan 05 '18 at 23:26
  • Possible duplicate of [how to set active class to nav menu from twitter bootstrap](https://stackoverflow.com/questions/15082316/how-to-set-active-class-to-nav-menu-from-twitter-bootstrap) – Arnold Gandarillas Jan 05 '18 at 23:44
  • Thanks the urls are ok, it prints the correct url in each link, the issue is when a submenu item is clicked the main item that englobes that clicked submenu item do not stay with the active classs. It just works for main items not submenu items. –  Jan 05 '18 at 23:51

1 Answers1

0

Note that sub-menus have 2 li elements as parents while a top menu item has only one li parent:

 $(this).parents('li').length == 2  => submenu
 $(this).parents('li').length == 1  => menu

Here is a working example:

$(document).ready(function () {

    $("#nav a").each(function() {
        // you can change here the menus href, for test purpose 
        // I choose 'create' menu link: 'https://stacksnippets.net/create'
        if (this.href == 'https://stacksnippets.net/create') {
             
            // check if sub menu
            if ( $(this).parents('li').length == 2 ) {
              $(this).parents('ul.collapse').siblings('a').addClass('active');
            } else {
              $(this).addClass("active");
            }
        }
    });

});
a.active{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="nav">
    <ul class="">
        <li><a href="url">Item 0</a></li>
        <li>
            <a href="#edit" data-toggle="collapse" aria-expanded="false">
               Item 1
            </a>
            <ul class="collapse" id="edit">
                <li><a href="/create">Create</a></li>
                <li><a href="/edit">Edit</a></li>
            </ul>
        </li>
        <li><a href="/posts">Item 2</a></li>
    </ul>
</nav>
YouneL
  • 8,152
  • 2
  • 28
  • 50