jQuery event delegation

Short and sweet this one. I’m displaying a list of items in a

element. The number of items in this list is not know beforehand and when the user starts scrolling to the bottom of the page more items are added to the table.

When the user clicks a row in the table, I need to display the data in the row in more detail. Since items are added to the table on the fly, I need something that doesn’t care whether the element was on the page all along or has been added dynamically.

Enter jQuery’s .on(…) function. (More here)

We can use this function to add a single click event that handles all the rows in our table.

Here is a simplified version of the table:

<table id="table">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
<tr>
...
</tr>
</tbody>
</table>

And the jQuery code that will handle the click event of the rows in the table.


$('#table').on('click', 'tbody tr', function (e) {
    ...
});

The code locates the table by its id and instead of binding to every row individually we use the .on(…) function to say that we want to bind the click (‘click’) event using the following selector (‘tbody tr’) and we specify a callback function to actually do something when the row is clicked (e contains the arguments for the click event).

Using .on(…) we do not require a click event on every single row in the table. This will drastically cut down the number of handlers that are listening on the page which in turn is good for performance. Be careful though, not specifying a selector (or setting it to null) will still bind the handler directly to the DOM element.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

*