Search code examples
jquerywordpressstoppropagationpropagation

jQuery propogation issue with WordPress menus


I am having an issue stopping propogration of jQuery with WordPress submenus.

Here is my script:

$("#menu-item-302900 a").click(function(){                                      
    $.get('/?deletecookie', function() {
        window.location.href = "/";
    });
    return false;
});

Generated HTML:

<ul class="tabset">
    <li id="menu-item-302900" class="active">
        <a href="/future-residents">Future Residents</a>
        <ul class="sub-menu">
            <li id="menu-item-304504"><a href="/apply-online/">Apply Online</a></li>
            <li id="menu-item-304505"><a href="/other/">Other Link</a></li>
            <li id="menu-item-304540"><a href="/other1/">Other Link 1</a></li>
        </ul>
    </li>
    <li id="menu-item-303026"><a href="/other2/">Other Link 2</a></li>
</ul>

The javascript is taking effect even when one of the sub-menu items is being clicked.

Of course, I tried amending the code with function(e){e.stopPropagation();} however this hasn't helped the issue.

Looking for a workaround that would limit the jQuery specifically to the element on the selected menu item and not any of the elements in the sub-menu.

Can anyone advise on a solution?

Thanks


Solution

  • At the moment you're using the "descendant selector"; which matches all a's under the ul. Instead, you could use the "child" selector, which is more restrictive:

    "#menu-item-302900 > li > a"