0
votes

I have the following javascript which i use for a mobile menu which works ok but when a submenu item that has another sub menu is clicked it doesnt only close that sub menu but it also closes the parent sub menu. Hope that makes sense. Any ideas on how to get it to just close that sub menu and not the parent sub menu ?

jQuery('.mobile-menu .sub-menu').hide();
jQuery(document).ready(function () {
jQuery('.mobile-menu .sub-menu').parent().find('a:first').removeAttr('href').css('cursor','default');

if (jQuery('.mobile-menu .menu-item-has-children').length > 0) {
    jQuery('.mobile-menu .menu-item-has-children').click(
    function (event) {
        jQuery(this).addClass('toggled')
        if (jQuery(this).hasClass('toggled')) {
            jQuery(this).children('ul').toggle();
        }
    });
}
});
1

1 Answers

1
votes

My guess looking from here is you need event.stopPropagation() as in:

jQuery('.mobile-menu .sub-menu').hide();
jQuery(document).ready(function () {
jQuery('.mobile-menu .sub-menu').parent().find('a:first').removeAttr('href').css('cursor','default');

if (jQuery('.mobile-menu .menu-item-has-children').length > 0) {
    jQuery('.mobile-menu .menu-item-has-children').click(
    function (event) {
        event.stopPropagation();
        jQuery(this).addClass('toggled')
        if (jQuery(this).hasClass('toggled')) {
            jQuery(this).children('ul').toggle();
        }
    });
}
});

* Update * I guess it's one of those days for me. After I answered that (and thanks for the points, btw), in the back of my mind I remember that there were recommendations that stopping propagation works but you should be careful when using it. It took me a bit to Google-fu to resurrect what the issue was. It's pretty well stated in this article, but the TL;DR is that is may have unintended side effects. This entry at jQuery Fundamentals has some other ideas. If it's working for you, fantastic, but you might want to put this in the back of your mind just in case.