1

I have a nested li

<li class="innerMenuLi"><a href="#"><span>MainLi</span></a>
<ul class="mainMenu">
    <li><a href="#" class="active"><span>mainMenu1</span></a></li>
    <li><a href=""><span>mainMenu2</span></a></li>
    <li><a href=""><span>mainMenu3</span></a></li>
    <li><a href=""><span>mainMenu4</span></a></li>
    <li><a href=""><span>mainMenu4</span></a></li>
    <li class="secondInnerMenu"><a href="#"><span>mainMenu5</span></a>
        <ul class="analyticsMenu">
            <li><a href="">secondInnerMenu1</a></li>
            <li><a href="">secondInnerMenu2</a></li>
            <li><a href="">secondInnerMenu3</a></li>
            <li><a href="">secondInnerMenu4</a></li>
        </ul>
    </li>
</ul>

$('.innerMenuLi').children('.mainMenu').click(function(e){
    e.stopPropagation();
    showMenu($(this));
});
$('.innerMenuLi').click(function(e){
    showMainMenu($(this));
    e.stopPropagation();
});
function showMainMenu(el){
    if(!el.hasClass('open')){
        (el).addClass('open');
        (el).children('.mainMenu').show();
    }else{
        (el).removeClass('open');
        (el).children('.mainMenu').hide();
    }
}
function showMenu(el){
    if(!el.hasClass('open')){
        (el).addClass('open');
        (el).children('.analyticsMenu').show();
    }else{
        (el).removeClass('open');
        (el).children('.analyticsMenu').hide();
    }
}

I want different functions to be called for the parent and child li.But now when the child is clicked it triggers the parent.

Thanks in advance

Adidev
  • 343
  • 2
  • 11

1 Answers1

2
// will prevent the event to bubble up the DOM and so avoid parent attached handlers to be triggered
e.stopPropagation();

Since the structure is the same for both menu levels, I would rather attach a single handler to the top menus container and test whether the click occurred against a <a> tag (followed by an ul element), then if true, process the sibling menu like so:

/* Event delegation menu click */
$('#root').on('click', function(e){
    var $t = $(e.target).closest('a'),
        $ul = $t.nextAll('ul').eq(0);
    if($t.length && $ul.length){
        $ul.toggleClass('open').slideToggle();
    }
});

fiddle Here

Stphane
  • 3,368
  • 5
  • 32
  • 47