JQuery: live vs delegate

When you want to attach event handlers to your HTML elements via JQuery, like the bind() method, but you want to include any elements added to the DOM after the method is executed, you could use the live() method or the delegate() method.

Q: So, which JQuery method should you use -- live or delegate?

This question is frequently asked and debated, and rightly so. More importantly, it's a useful question but one that's often overlooked. Here is a summary of live and delegate, and the key differences between them that developers should be aware of. There are numerous blog posts and answers about this, and I link to a few typical examples here. The answer is intuitive when you compare and contrast the commonly used JQuery methods for binding events to HTML elements: live, delegate and bind.

A: In general, it's best to use the delegate() method rather than the live() method.

There are two main reasons underpinning this conclusion:

As one developer has phrased it: "I consider the benefits of using delegate to be so substantial as to be overwhelming". It's worth noting that delegate() uses live() internally, and the two methods fundamentally work in the same way and offer the same basic functionality (see "the difference between live and delegate"). The one notable advantage that live has over delegate is the simpler syntax, thus you might find it acceptable to use live for convenience when prototyping.

31 October 2011

Share the love:


  • Twitter
  • LinkedIn
  • Facebook
  • Windows Live / Messenger
  • Xbox Live
  • RSS
  • Email