I’ve read some posts here and elsewhere on the web about the differences between live() and delegate(). However I haven’t found the answer I’m looking for (if this is a dupe please tell me).
I know that the difference between live and delegate is that live cannot be used in a chain. I also read somewhere that delegate is in some cases faster (better performance).
My question is, is there a situation where you should use live instead of delegate?
UPDATE
I’ve set up a simple test to see the difference in performance.
I’ve also added the new .on() which is available in jQuery 1.7+
The results pretty much sum up the performance issues as stated in the answers.
- Don’t use
.live()unless your jQuery version doesn’t support.delegate(). - Don’t use
.delegate()unless your jQuery version doesn’t support.on().
The difference between .live() and .delegate() is A LOT bigger than between delegate() and .on().
I never use
live; I consider the benefits of usingdelegateto be so substantial as to be overwhelming.The one benefit of
liveis that its syntax is very close to that ofbind:delegate, however, uses a slightly more verbose syntax:This, however, seems to me to be much more explicit about what is actually happening. You don’t realise from the
liveexample that the events are actually being captured ondocument; withdelegate, it is clear that the event capturing happens on#containerElement. You can do the same thing withlive, but the syntax becomes increasingly horrid.Specifying a context for your events to be captured also improves performance. With the
liveexample, every single click on the entire document has to be compared with the selectora.myClassto see if it matches. Withdelegate, that is only the elements within#containerElement. This will obviously improve performance.Finally,
liverequires that your browser looks fora.myClasswhether or not it currently exists.delegateonly looks for the elements when the events are triggered, giving a further performance advantage.NB
delegateuseslivebehind the scenes, so you can do anything withlivethat you can do withdelegate. My answer deals with them as they are commonly used.Note also that neither
livenordelegateis the best way to do event delegation in modern jQuery. The new syntax (as of jQuery 1.7) is with theonfunction. The syntax is as follows: