Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent firing its parent's click event on Clicking a child element [duplicate]

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.

like image 923
Maven Avatar asked Oct 13 '13 10:10

Maven


1 Answers

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.

like image 188
Kundan Singh Chouhan Avatar answered Oct 20 '22 12:10

Kundan Singh Chouhan