Gai Kuroda
Gai Kuroda

Reputation: 80

stopPropagation() does not work for delegate event

i am trying to toggle .abb-bar, using $.toggle() whenever its parent( .abb ) gets a click. but whenever .abb-bar gets a click, its toggles itself because of event-bubbling. e.stopPropagation() should solve the problem but it does not work. what can be done?

HTML

<span class="col-auto entry-ops abb">
    <i class="fa fa-bars"></i>
    <div class="list-group abb-bar">
        <button class="list-group-item list-group-item-action d-flex justify-content-center" data-user="nick">follow</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center complain">complain</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center show-entry-number" data-toggle="tooltip">'.$row['entry_id'].'</button>
    </div>
</span>

JS

$(document).on('click', '.abb', function( e ) {
    e.stopPropagation();
    $(this).children('.abb-bar').toggle();
});

Upvotes: 2

Views: 2144

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65796

You shouldn't be using event delegation here.

By the time the event reaches document, there's only one more element for it to propagate to (window). It has already propagated up to document so you can't retroactively cancel it for elements it's already fired on. This is the very nature of event delegation... Let the event bubble all the way up and then see which element originated the event.

You only need to set a click event on the toggle element and cancel the click event on the child container.

// Set the click event handler on the toggle area
$('.abb').on('click', function( e ) {
    $('.abb-bar', this).toggle();
});

// Don't enable the click event on the child
$('.abb-bar').on('click', function( e ) {
    e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="col-auto entry-ops abb">
    <i class="fa fa-bars">Click to toggle</i>
    <div class="list-group abb-bar">
        <button class="list-group-item list-group-item-action d-flex justify-content-center" data-user="nick">follow</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center complain">complain</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center show-entry-number" data-toggle="tooltip">'.$row['entry_id'].'</button>
    </div>
</span>

Upvotes: 3

Related Questions