0

I followed the explanation below to create what I needed, but there is an additional requirement i am trying to fulfill.

highlight the navigation menu for the current page

My submenu items are anchor links on the same page as the main menu item. Example:

$(function() {
        var url = window.location.href;
        $(".imagingmenu a").each(function() {
            if (url == (this.href)) {
                $(this).closest("li").addClass("active");
               $(this).closest("li").parent().parent().addClass("active");
            }
        });
    });
.imagingmenu ul li.active a, .imagingmenu ul li a:hover {
font-weight:bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="imagingmenu">

<ul>
<li><a href="http://exampleurl-1.com">Menu item 1</a>

<li><a href="#">Menu item 2</a>

<ul>
<li><a href="#/#submenuitem1">Submenu Item 1</a></li>
<li><a href="#/#submenuitem2">Submenu Item 2</a></li>
<li><a href="#/#submenuitem3">Submenu Item 3</a></li>
</ul>

</li>
</ul>

</div>

You can see the bolding works when you hover over the submenu items, but when they are clicked and active, I want just that submenu item to be bolded and the other not to be. However, when any of the submenu items are active, all of them in the list are bolded. How can I achieve what I'm looking for?

Thanks.

Stephen P
  • 14,422
  • 2
  • 43
  • 67
Eric Sayag
  • 45
  • 5
  • When you create your code snippet, there's an option on the left to import jQuery + other libraries, so that your code snippet will actually run. – Alicia Sykes May 04 '22 at 21:08
  • With your use of `.parent().parent()` you are going up 2 levels in the DOM tree from the `li` selected by `$(this).closest("li")` — So you are adding **active** to the `
  • ` itself, and also to the `
      ` or the `
      ` depending on if you clicked a menu item or a submenu item. This doesn't seem to make a difference give the code you're showing, but it's odd.
  • – Stephen P May 04 '22 at 21:32