What is the difference between the bind and live methods in jQuery?
Solution 1
.bind() attacheds events to elements that exist or match the selector at the time the call is made. Any elements created afterwards or that match going forward because the class was changed, will not fire the bound event.
.live() works for existing and future matching elements. Before jQuery 1.4 this was limited to the following events: click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup
Solution 2
In short: .bind()
will only apply to the items you currently have selected in your jQuery object. .live()
will apply to all current matching elements, as well as any you might add in the future.
The underlying difference between them is that live()
makes use of event bubbling. That is, when you click on a button, that button might exist in a <p>
, in a <div>
, in a <body>
element; so in effect, you're actually clicking on all of those elements at the same time.
live()
works by attaching your event handler to the document, not to the element. When you click on that button, as illustrated before, the document receives the same click event. It then looks back up the line of elements targeted by the event and checks to see if any of them match your query.
The outcome of this is twofold: firstly, it means that you don't have to continue reapplying events to new elements, since they'll be implicitly added when the event happens. However, more importantly (depending on your situation), it means that your code is much much lighter! If you have 50 <img>
tags on the page and you run this code:
$('img').click(function() { /* doSomething */ });
...then that function is copied into each of those elements. However, if you had this code:
$('img').live('click', function() { /* doSomething */ });
...then that function is stored only in one place (on the document), and is applied to whatever matches your query at event time.
Because of this bubbling behaviour though, not all events can be handled this way. As Ichiban noted, these supported events are click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup.
Solution 3
Nice read on this: http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
Is nowadays (since jQuery 1.7) deprecated using the .on() function - http://api.jquery.com/on/
Solution 4
Bind will bind events to the specified pattern, for all matches in the current DOM at the time you call it. Live will bind events to the specified pattern for the current DOM and to future matches in the DOM, even if it changes.
For example, if you bind $("div").bind("hover", ...) it will apply to all "div"s in the DOM at the time. If you then manipulate the DOM and add an extra "div", it won't have that hover event bound. Using live instead of bind would dispatch the event to the new div as well.
Solution 5
imagine this scenario:
- i have several
<img>
elements.$('img').bind('click', function(){...});
- add some extra images (using
get()
, orhtml()
, anything) - the new images don't have any binding!!
of course, since the new images didn't exist when you did the $('img')...
at step 2, it didn't bind the event handler to them.
now, if you do this:
- i have several
<img>
elements.$('img').live('click', function(){...});
- add some extra images (using
get()
, orhtml()
, anything) - the new images do have the binding!!
magic? just a little. in fact jQuery binds a generic event handler to another element higher in the DOM tree (body? document? no idea) and lets the event bubble up. when it gets to the generic handler, it checks if it matches your live()
events and if so, they're fired, no matter if the element was created before or after the live()
call.
Kevin Brown
Currently working as a rails developer for [Fleetio] After obtaining a degree in Mechanical Engineering with an energy specialty. After that, I worked 1 year for Babcock & Wilcox in nuclear services; then moved to work for Honda for the next 4+. During that time, I spent every moment learning ruby/rails/js and now love what I do as a software engineer.
Updated on July 08, 2022Comments
-
Kevin Brown almost 2 years
I'm curious to know the differences between the bind and live functions.
To me they seem to be almost identical.
I read the benefits of live/bind methods, but it didn't tell me about the differences...
Thanks!
-
Kevin Brown almost 15 yearsYou're right. .live is a must for ajax events, though, right?
-
Nosredna almost 15 yearsWhy do you say that? I've found that live simplifies the code. I'm pretty picky about performance, and it seems fine to me. What's the downside?
-
andi almost 15 yearsWell, first of all because not all events are available with live(). Secondly, because I think they are harder to manage (no stopPropagation and stopImmediatePropagation), and third because live() surely generates more overhead than bind() (as it looks for changes in the DOM). Maybe not a killer difference, but still. That's why I tend to stick to bind() where possible.
-
eyelidlessness over 14 yearslive() doesn't look for DOM changes, it maintains a list of target selectors and checks them at event time (the events fire on
document
). There is some overhead, but it's very minimal. The real danger is that some uses oflive
can cause garbage collection to fail. -
eyelidlessness over 14 yearsOr you can use proper event delegation, bind the events to
document
, and check the event's target. -
harpo about 14 yearsThanks for the explanation of how this works. The jQuery documentation doesn't explain any of this, which seems important for using it.
-
Josh Smith over 13 yearsFor anyone reading this now,
.live()
is no longer limited to the events listed above. The.live()
event now has support in jQuery 1.4 for all events, including custom events. -
mikkelbreum almost 13 years@meagar: "Because of this bubbling behaviour though, not all events can be handled this way. As Ichiban noted, these supported events are click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup." So now that it works for all events in later versions of jQuery, is it still working by being attached to the body and triggered when the body finally receives the bubbled event, or did that change?
-
mikkelbreum almost 13 yearsthis answer does not really answer the question, see below answer by nickf for the requested explanation
-
Minh Le over 12 yearsThanks, awesome answer, easy to understand.
-
Eduard Luca about 12 yearsGreat answer! Really helps to understand what goes on in the code. Was actually looking for this. Big +1 from me!
-
Ben almost 12 yearsBind is just a poor and limited live… why on earth does it still exists ?
-
aroth about 11 yearsI'm not sure I agree with the rationale of why
live()
is a 'lighter' solution. Yes, in the example, theclick()
handler will be copied 50 times. But that happens (and the copies are stored) behind the scenes, and it only happens once. Additionally the execution of the handler function is simpler in that case, since there's no need to inspect where the event came from and match selectors before invoking the actual event handler. Solive()
is lighter in terms of space and setup time, but slightly heavier in terms of runtime processing. -
aroth about 11 yearsEdit: I'm not even sure it would be copied 50 times; I think what you probably end up with is 50 references to a single copy, with jQuery making clever use of
apply()
and/orcall()
to set the value ofthis
appropriately each time the event handler is triggered. That's how I'd do it anyways. I suppose checking the source code is the only way to know for sure though. -
nickf about 11 yearsaroth - you're completely correct. I was young and stupid when I wrote this answer, but never got around to correcting it.
-
Joe.wang about 11 years@nickf I can learn a lot from your answer , thanks, But I have a question for you ,what you mean is event bubble or event capture ? becuase event bubble goes up but capture goes deep , thanks.
-
Joe.wang about 11 yearsWhat I can contribute this answer is the live() method can only be used on selectors, and can’t be used on derived wrapped sets.
-
Joe.wang about 11 yearsand more is seems
live
triggers the event by the script.not use the event handler.