Search code examples
javascriptjqueryevent-bubbling

Click event handler inadvertently bubbles, even after calling jQuery's stopPropagation()


I'm trying to have different delegate click handlers for different elements within "li" elements in a list. Example:

<ul id='myList'>
  <li>
    <p>First item.</p>
    <button>button1</button>
    <button>button2</button>
  </li>
  <li>
    <p>Second item.</p>
    <button>button1</button>
    <button>button2</button>
  </li>
</ul>

when the user clicks button1 (of any item) I want to grab that event, and stop propagation (same for button2 instances). The user clicking the parent li element would be a different handler:

$('#myList').delegate('li', 'click', function() {
    alert("You clicked a parent <li> item!");
});

$('#myList').delegate('button', 'click', function(event) {
    event.stopPropagation();
    event.stopImmediatePropagation();
    alert("You clicked a button (but which one?)!");
});

So one issue is, how do I have a delegate for button1 instances, and another for button2 instances? The second delegate in the example above does fire when a button is clicked, but event.stopPropagation() doesn't seem to work as the handler for the parent li item still gets called,

------ Update --------------

Also trying to call event.stopImmediatePropagation(), no effect though, parent handler still being called too.

Thank you


Solution

  • Maybe in the parent:

    $('#myList').delegate('li', 'click', function(event) {
        if (!$(event.target).is('button')) {
            alert("You clicked a parent <li> item!");
        }
    });