Search code examples
javascriptjqueryevent-delegation

Is there a rule of thumb for when to use event delegation vs event handling in JQuery?


I'm confused about when you should use event delegation as opposed to out-of-the-box JQuery event handling.

I'm always tempted to use an event handler because it's so easy in JQuery:

For example:

$("button#submit").click(function () { 
      $(this).css("disabled", "true");
    });

Event delegation is not really that much more complex to write:

$("button#submit").live("click", function() {
      $(this).css("disabled", "true");
});

But it just doesn't seem as intuitive.

Is there a simple rule of thumb about when to use event delegation? I guess I don't really understand the point of it.


Solution

  • You should use event delegation in the following situations:

    • When you want to handle the same event across many elements, e.g. if you have a data table with many rows, using delegation will use much less memory and be faster than registering an event handler per row.
    • When elements are dynamically added to the page after page load and you want to handle events for these new elements, e.g. adding rows to a data table.

    Using Event Utility and Event Delegation to Improve Performance disusses this some more (even though the article uses YUI the ideas are still applicable).