Tuesday, June 29, 2010

Quick Tip: Use jQuery live() Function For Links in JavaScript-Powered Data Tables

NOT doing the tip that I'm about to share has bitten me twice now, so I'm putting this out there as a reminder to myself as well.

The jQuery live() function is an extremely useful function to have when you're adding or removing page elements that have jQuery event handlers assigned to them because using live() ensures that any new element that matches the live() selector gets that event handler automatically.

It's easy to remember to use live() when you're writing your own code that adds and removes DOM elements, but when you're using a plugin that does the adding and removing behind the scenes, you might not think about it.  In one of my applications, I apply the jQuery DataTables plugin to my HTML tables so that the users can sort and filter the data in the tables.  Included in each row are hyperlinks that trigger certain actions via JavaScript/jQuery. 

When I originally assigned the event handlers to these links, I simply used the "click" event handler on them.  The links worked perfectly if they were displayed as part of the initial page load, but any links belonging to rows that appeared later (as the result of a sort, filter, or pagination event in the plugin) did not work because the link elements were actually added by the plugin, and hence did not have the event handlers assigned to them.

In short, if you're using one of the many plugins to enhance HTML tables, and you have elements in each row that have jQuery events assigned to them, make sure you use the live() function to assign those event handlers.

No comments:

Post a Comment