In jQuery, if you want to observe an event on certain element, you can choose to use .bind() or .live().
$('#page_title').bind('click', function(){
$(this).html('you clicked me');
});
Alternatively, you can write the above using shortcut:
$('#page_title').click(function(){
$(this).html('you clicked me');
});
However, the first format allows you to bind multiple events to the same element with same call back method.
$('#page_title').bind('mouseover mouseout', function(){
$(this).html('you didn't me');
});
In jQuery, you can also use .live() method.
$('#page_title').live('click', function(){
$(this).html('you clicked me');
});
According to jQuery doc, .live() attaches a handler to the event for all elements which match the current selector, now or in the future. The difference lies in the word in the future. You could attach a handler to the event for the element even the element doesn’t exist! So you could run the following code before the document is fully loaded.
$('#page_title').live('click', function(){
$(this).html('you clicked me');
});
However, if you use .bind() method, you must make sure that the document element already exists before you observe it. Otherwise, the event handler won’t be triggered. This is especially useful when you are using Ajax in your website. You could observe the element before the Ajax loads. So you don’t have to rebind the event to the element everytime Ajax finished loading.E.g, normally you will do this :
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
$('#page_title').live('click', function(){
$(this).html("you clicked me");
});
}
});
This is very troublesome and every time you have to reattach those event handlers to the event on the elements. So what you could is adding the event observer even before you add the Ajax:
$('#page_title').live('click', function(){
$(this).html("you clicked me");
});
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
//...anything here
}
});
But do you find any problem with the above code?
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
$('#page_title').live('click', function(){
$(this).html("you clicked me");
});
}
});
Yes, you shouldn’t use .live(), you should use .bind() instead. If you use .live() here, then every time the Ajax finished loading, the element will add a event handler, although they are the same functionality but different reference. So the Ajax loads twice, you click on the ‘page_title’, it should alert twice.
So remember to use .live() on the same element once only.
Read the rest of this entry »


