JavaScript event delegation explained with practical examples

JavaScript event delegation, with practical examples

A click handler attached with addEventListener works only for elements that exist at that moment. Products loaded by “load more”, comments added by AJAX, rows inserted by a filter: their buttons do nothing, because nobody attached a handler to them. Event delegation solves it with one listener on a parent element that exists from the start.

Problem: “Add to cart” buttons in products loaded with AJAX do not react to clicks, while the ones that were on the page from the start work.

Solution: Attach one listener to a container that is always there, and in the handler find the clicked element with event.target.closest( selector ). Events bubble up from the clicked element to its parents, so the container sees clicks on elements added later.

The pattern

var list = document.querySelector( '.products' );

if ( list ) {
    list.addEventListener( 'click', function ( event ) {
        var button = event.target.closest( '.add-to-cart' );

        if ( ! button || ! list.contains( button ) ) {
            return; // the click was somewhere else in the list
        }

        event.preventDefault();
        addToCart( button.dataset.productId );
    } );
}

closest() matters: the user may click the icon or the text inside the button, and then event.target is the <span> or <svg>, not the button itself. closest() walks up to the nearest element that matches the selector.

New products appended to .products later need no extra code:

list.insertAdjacentHTML( 'beforeend', '<li><button class="add-to-cart" data-product-id="99">Add</button></li>' );
// clicks on the new button are handled by the same listener

Other events

// Changes of any select in a form, also fields added later
document.querySelector( '#checkout-form' ).addEventListener( 'change', function ( event ) {
    if ( event.target.matches( 'select[name="shipping_method"]' ) ) {
        updateShipping( event.target.value );
    }
} );

Most events bubble: click, input, change, submit, keydown. focus and blur do not; delegate focusin and focusout instead. mouseenter and mouseleave do not bubble either; use mouseover and mouseout.

jQuery

jQuery( '.products' ).on( 'click', '.add-to-cart', function ( event ) {
    event.preventDefault();
    addToCart( jQuery( this ).data( 'product-id' ) );
} );

The second argument turns the handler into a delegated one, and this is the matched button, not the clicked child element.

Where to attach

Choose the closest container that exists on page load and contains all the elements: the product list, the comment list, the form. Attaching everything to document works too, but then every click on the page runs every delegated check, and stopPropagation() anywhere on the way up silently breaks the handler.

NOTE: If a plugin’s script calls event.stopPropagation() on clicks (some sliders and modals do), the event never reaches your container. When a delegated handler mysteriously stops working inside one component, that is the first thing to check.