1

I have a bootstarp multi-level side menu (not using jQuery UI menu). Unfortunately, when I click a submenu item, all its parents are triggered as well.

This is because i have nested <li> elements with 'nested' id names. I need nested names in order to easily take all children content from the DB. jQuery UI .menu() method works well, but it is badly stylized. So I use custom sidebar with custom click() event.

How can I tell jQuery to handle only one, the deepest <li> element clicked?

HTML

<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" style="display: block; position: static; margin-bottom: 5px; *width: 180px;">
  <li id="m1-" class="dropdown-submenu"><a href="#">Grandfather</a>
  <ul class="dropdown-menu">
    <li id="m1-1-" class="dropdown-submenu"><a href="#">Father</a>
    <ul class="dropdown-menu">
       <li id="m1-1-1" ><a href="#">Son</a></li>
    </ul>
    </li>
  </ul>
  </li>
</ul>

Javascript (to handle click in IDs that start with 'm', i.e. menu items)

$("li[id^='m']").click(function(){
  //my code to handle the click
});

And yeah, I see now that the 'm' preffix is not a right preffix, should be more unique like 'menu'. I will fix it later.

artildo
  • 79
  • 8
  • @ShaunakD It means that when i click on the Son, only Son will be executed, not Father and Grandfather items. – artildo Jul 14 '14 at 10:55

4 Answers4

11

You can prevent the propagation of the event from the handler so that the ancestor element's handlers will not get executed

$("li[id^='m']").click(function(e){
  e.stopPropagation()
  //my code to handle the click
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

Well you can stop the event to bubble up;

$("li[id^='m']").click(function(ev){
  //my code to handle the click
    ev.stopPropagation();
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0

use stopPropagation to prevent the bubbling event

 $("li[id^='m']").click(function(e){

    e.stopPropagation();
      //my code to handle the click
    });

note: In your dom structure li nested with another li ..so it could be bubbled event when you click

Balachandran
  • 9,567
  • 1
  • 16
  • 26
-1

Try:

$("li[id^='m']").click(function(e){
    e.stopPropagation();
    e.preventDefault();
});
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
dhalfageme
  • 1,444
  • 4
  • 21
  • 42