Best practice to avoid memory or performance issues related to binding a large number of DOM objects to a click event

The most efficient way to bind a large number of similar elements to a single event is to make use of event bubbling. You attach a single event handler to a common parent object and then, in the single event handler, you examine which object the event originated in to see if the original object is an object you’re monitoring for this event.

For attaching the event, it costs you only a single event handler and you can serve an infinite number of child objects from that one event handler.

There’s a slight performance degradation at the run-time of each event (probably not noticeable) because the event has to bubble up to a parent before the event handler sees it and the event handler has to check if the source object is a desired target object or not. But, it’s massively more efficient to install the one single event handler rather than installing thousands of individual event handlers.

Delegated event handling also has the advantage that it works well for dynamically created objects, even objects created after the event handler was installed – something that doesn’t not work well for event handlers installed directly on the objects themselves (non-delegated event handlers).

In jQuery, you can use delegated event handling like this:

$(common parent selector).on('click', selector of target objects, function() {});

For example, HTML:

<div id="parent">
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
    <button class="addButton">Add</button>
</div>

Code:

$("#parent").on('click', ".addButton", function(e) {
    // the value of `this` is set to the object that originated the event
    //     e.g. what was clicked on
});

Leave a Comment