Search code examples
javascriptjqueryjquery-eventsevent-delegation

How to filter out child element events in a event handler?


I have bootstrap button-group. Also, a jQuery based event handler (uses event delegation) that sets/unsets the bootstrap .active class on the appropriate .btn based on click event.

The problem happens when my buttons have html elements inside it. When you click on the child element of a button, the .active class is set on the .btn's child elements.

How do I only receive events for the precise elements I am interested in ?

http://jsfiddle.net/0nc3wjq4/ To reproduce the problem, please click on one of the numbers in a button and then click on another number in a different button.

    <div class="btn-group btn-group-justified pipeline" role="group">
      <a href="#" class="btn btn-default" role="button">
        <h3 class="text-center">767</h3>
        <p class="text-muted text-center">Stage1</p>
      </a>
    </div>

Event Handler

$( ".btn-group" ).on( "click", ".btn", function( e ) {
    $(this).siblings(".active").removeClass('active'); // previous
    $(e.target).addClass('active'); // current
});

Solution

  • replace $(e.target) with $(this)

    e.target is showing as the h3/p and not the button

    e.target is the element that triggered the event, ie - the h3 you clicked which propagated the event on to the a.btn. That then got caught by your event handler.

    this is the element which triggered the handler.