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.

Sander Harrewijnen

Author Sander Harrewijnen

Als ontwikkelaar mag ik graag problemen oplossen en nieuwe functionaliteit bouwen. Vanuit mijn creatieve kant hou ik me ook graag bezig met hoe iets bij de eindgebruiker aankomt. Je kunt bij mij dus ook terecht voor de opmaak en layout van een oplossing. Als je mij wilt afleiden, dan lukt dat altijd met een coole nieuwe gadget. Dat is namelijk mijn andere passie.

More posts by Sander Harrewijnen
19 September 2012

Leave a Reply