Sometimes you have a set of elements when the page loads, like, say, edit links:
<table>
<tr>
<td>Item 1</td>
<td><a href="#" class="edit">Edit</a></td>
</tr>
<tr>
<td>Item 2</td>
<td><a href="#" class="edit">Edit</a></td>
</tr>
<tr>
<td>Item 3</td>
<td><a href="#" class="edit">Edit</a></td>
</tr>
</table>
Now, maybe you have something like this with jQuery:
$(document).ready(function() {
$('a.edit').click(function() {
// do something
return false;
});
});
But what if you add a new element to this table dynamically, after the page has initially loaded?
$('table').append('
<tr><td>Item 4</td><td><a href="#" class="edit">Edit</a></td></tr>
');
When you click on "Edit" on this new Item, nothing will happen because the events were bound on page load. Enter live. With it, you can bind the event above like this:
$(document).ready(function() {
$('a.edit').live('click', function() {
// do something
return false;
});
});
Now if you add any new <a>
elements with a class of edit
after the page has initially loaded, it will still register this event handler.
But how is this accomplished?
jQuery uses what is known as event delegation to achieve this functionality. Event delegation is helpful in this situation or when you want to load a large amount of handlers. Say you have a DIV with images:
<div id="container">
<img src="happy.jpg">
<img src="sad.jpg">
<img src="laugh.jpg">
<img src="boring.jpg">
</div>
But instead of 4 images, you have 100, or 200, or 1000. You want to bind a click event to images so that X action is performed when the user clicks on it. Doing it as you might expect...
$('#container img').click(function() {
// do something
});
...would then bind hundreds of handlers that all do the same thing! This is inefficient and can result in slow performance in heavy webapps. With event delegation, even if you don't plan on adding more images later, using live can be much better for this kind of situation, as you can then bind one handler to the container and check when it is clicked if the target was an image, and then perform an action:
// to achieve the effect without live...
$('#container').click(function(e) {
if($(e.target).is('img')) {
performAction(e.target);
}
});
// or, with live:
$('img', '#container').live('click', function() {
performAction(this);
});
Since jQuery knows that new elements can be added later on or that performance is important, instead of binding an event to the actual images, it might add one to the div like in the first example (in reality, I'm pretty sure it binds them to the body but it might to the container in the example above) and then delegate. This e.target
property can let it check after the fact if the event that was clicked/acted on matches the selector that you might have specified.
To make it clear: this is helpful not only in the direct way of not having to rebind events, but it can be dramatically faster for a large amount of items.