Posted over 10 years ago. Visible to the public. Repeats.

Efficiently add a click event handler to many elements

When you need to add a click event handler to 50+ elements, this might slow down the browser.

An alternative is to register an event at the root of the DOM tree (document). Then wait for events to bubble up and check whether the triggering element (event.target) matches the selector before you run your callback.

Examples

For the examples below let's assume we have many <a class="dialog-link" ...> elements on our page. Clicking them should open a modal dialog.

Native JavaScript

Copy
document.addEventListener('click', function(event) { if (event.target.closest('.dialog-link')) { // Open dialog } });

Unpoly

Copy
up.on('click', '.dialog-link', function(event, link) { // Open dialog });

jQuery

Copy
$(document).on('click', '.dialog-link', function(event) { // Open dialog });

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Henning Koch
Last edit:
4 days ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more