0
votes

I have a WordPress menu with a dropdown. I have CSS code to underline the selected menu item when it is active. This works for both root level menu items and sub-menu items. I would like to do is set the dropdown to active when one of the sub-menu items is clicked. I'm trying this in jQuery.

jQuery(function($) {
    $(".navbar .nav .nav-item.dropdown li").click(function() {
        $(".navbar .nav .nav-item.dropdown").addClass('active');
    });
}

It almost works. When I click the sub-menu item, I can see the dropdown go active, but then it goes right back to not active. I think that's happening is the jQuery fires and sets the dropdown to active and then the page reloads and that active is wiped out.

Any idea how I can make it stick?

2

2 Answers

0
votes

After thinking about it, I realized that was severely overthinking this. I needed to look at the sub-menu items after the page loads. That's the first thing that I was doing incorrectly. After that, all I needed to do is get a list of sub-menu items, check to see if any of them have the active class and if they do, set the dropdown item to active. Below is the code that does this for me. Is there a better way?

$(window).load(function (e) {
    var listItems = $('.navbar ul li ul.dropdown-menu .nav-item');

    //Loop the listitems and check to see if any are active.
    $.each(listItems, function(key, litem) {
        if ($(litem).hasClass('active')) {
            $(".navbar .nav .nav-item.dropdown").addClass('active');
            return false;
        }
    })
})
0
votes

reason why it get's remove is because you run function on click rather then when you load new subpage.

So what you could do is when you land on the page have a jQuery function that checks if any of sub-menu items is active and then addClass to the parent.

As I am not sure is this custom made menu or WP menu lets assume you have structure like this:

<ul class="parent-menu">
  <li>Parent Item
    <ul>
      <li class="someSubMenuClass active">Child Item</li>
    </ul>
  <li>
</ul>

What you could do at this moment is use jQuery.closest('.parent-menu') to find closest parent element with class parent-menu and after you have found that you need to addClass to that element. So it might look like this:

$( document ).ready(function() {
  $( "li.someSubMenuClass.active" ).closest('.parent-menu').addClass('active');
});

Note that I am not sure about your structure so you might need to update the structure but this should work fine.