0

I want to save the current items class id, when i click on a menu item. The problem is, that when i click on a submenu item, it will run the jQuery multiple times, because the items classes have the same name. So the javascript alerts more than one time. It seems as when a parent li has the same class name as the child, it will run the jQuery code for both of them. How can i avoid the jQuery to run for the parent li ?

html:

<li id="menu-item-2139" class="menu-item">Item 1
    <ul class="sub-menu">
        <li id="menu-item-2151" class="menu-item">Item 2</li>
        <li id="menu-item-2564" class="menu-item">Item 3
            <ul class="sub-menu">
                <li id="menu-item-2567" class="menu-item">Item 4</li>
                <li id="menu-item-2570" class="menu-item">Item 5</li>
            </ul>
        </li>
    </ul>
</li>

jQuery:

jQuery('.menu-item').click(function(){
    var class_id = jQuery(this).attr('id');
    alert(class_id);
});
1

It's called "event bubbling" or "event propagation" and the solution is to get the event object and use the JS stopPropagation method. Try this:

jQuery('.menu-item').click(function(event){
    var class_id = jQuery(this).attr('id');
    event.stopPropagation();
    alert(class_id);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.