bevacqua
bevacqua

Reputation: 48486

How does jQuery .live() work?

I was thinking about performance regarding

.click() vs .live("click")

and that left me wondering about how .live does work.

Does it monitor DOM changes and when it detects a change in the DOM it just attaches the event then, does it use some sort of timer (I wouldn't think so, but if it did this is very important, timers make me a sad person)

Upvotes: 8

Views: 2382

Answers (5)

Geoff Appleford
Geoff Appleford

Reputation: 18832

live binds the click event to the DOM's document element. As browser events bubble up through the DOM tree, the click event is triggered for any matching elements.

Here's a good article explaining it all.

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

Upvotes: 12

lbrandao
lbrandao

Reputation: 4373

From the jQuery manual on .live():

The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.

As you see, there is no timer involved.

Upvotes: 2

ShankarSangoli
ShankarSangoli

Reputation: 69905

.live do not attach events to every element in the dom even when the dom changes. It listens event to the root element like body or any container on which the live is attached. Once the event in the inner level element is triggered it checks for the target and matches with the selector specified in the live and if it matches it raises that event.

Upvotes: 2

Rafay
Rafay

Reputation: 31033

if you are adding elements to the DOM dynamically and want the click handler to be atached to them you will have to use live or delegate but if you are not simply use click

Upvotes: 0

Related Questions