Search code examples
javascriptjqueryonclickevent-propagation

One click handler for multiple buttons and stop propagating event up to parent?


I'm generating a bunch of "li" items as a result of an ajax call. They look like:

<li>
  <p>Hello result 1</p>
  <button>remove</button>
</li>    
<li>
  <p>Hello result 2</p>
  <button>remove</button>
</li>
...

can I create a single click handler that will get called when any one of the "li" item "button" elements gets clicked, and will also stop propagating the click event up to the "li" parent? Something like:

function btnClicked() {
    var liItem = this.parent; // ideally is the <li> whose button was clicked.
    return true; // don't let click event go up to <li> parent?
}

----------------- Edit ---------------------

Also, I'm not sure if I'm going to use the button element, might use a clickable div as a button instead - the same techniques should work for both though, right?

Thank you


Solution

  • $('li').click(function(event) {
    //do something
    event.stopPropagation()
    });
    

    This will work in jQuery. You will want to change the li to select only the li items you want.