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.

Related articles

  • Cloud Native
  • Application Navigator
  • Kubernetes Platform
  • Digital Workspace
  • Cloud Infrastructure
  • ITTS (IT Transformation Services)
  • Managed Security Operations
  • Multi-Cloud Platform
  • Backup & Disaster Recovery
Visit our knowledge hub
Visit our knowledge hub
Sander Harrewijnen Developer

Let's talk!

Knowledge is key for our existence. This knowledge we use for disruptive innovation and changing organizations. Are you ready for change?

"*" indicates required fields

First name*
Last name*
Hidden