11

I have a following menu that drills down to three levels: Main > sub > subsub

<nav>
      <div class="mainMenu">Main Menu Item # 1.
                    <ul>
                        <li> Sub Menu Item # 1</li>
                        <li class="subMenu"> Sub Menu Item # 2
                            <ul>
                                <a href="New">
                                    <li>New</li>
                                </a>
                                <a href="">
                                    <li>Old</li>
                                </a>
                                <a href="">
                                    <li>View </li>
                                </a>
                            </ul>
                             <div class="n_r2_c2"></div>
                        </li>
                        <li> Sub Menu Item # 3</li>
                        <li> Sub Menu Item # 4</li>
                    </ul>
  </div>

And this as my JQ:

$('.mainMenu').click(function () {
    $(this).children('ul').slideToggle(250);
});

$('.subMenu').click(function () {
        $(this).children('ul').slideToggle(250);
});

The issue is sub menu toggling for main’s sub menu works fine, but when I click an item in sub menu it instead of toggling its sub menu, it closes itself because when I am clicking on the submenu the main menu click event is also gets fired most probably because the sub menu is inside it and it takes the click on it as a click on the main div?

In anyways how can I solve this issues, please help.

Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53
Maven
  • 14,587
  • 42
  • 113
  • 174

1 Answers1

18

Use event.stopPropagation() to prevents the event from bubbling up the DOM tree.

Example:

$('.subMenu').click(function (e) {
    $(this).children('ul').slideToggle(250);
    e.stopPropagation();
});

This will fix your issue.

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32