in Uncategorized

JQuery Event Delegation

Came across a awesome way of handling events using JQuery’s event delegation methods.   I have a list of A tags grouped in a table, and each A tag will call a method and pass a ID based on a value in the same column of that A tag.

jQuery(“#tableId”).click(function(event) {
var $target = jQuery(event.target), target = event.target;
if ($target.parents(“a:first”).is(“a.editNote”)) { //Make sure that we have found the right A tag
var id = parseInt($target.parents(“tr:first”).find(“td:first a”).text()); //traverse back through the parents to view the corresponding ID which is in another A tag
callFunction(id);
}
});

This is way better than doing a typical jQuery(“a[id=editNote”].click(function) as this creates a event handler for each A tag.   Using Event Delegation like above only creates one handler which has less overhead on browsers (especially IE).