How To Add Back jQuery .live() & .die() Function


As you may know, jQuery removed .live() function and instead they told to use .on() function. But I didn’t like this because .on() needs up more parameters than .live() and to handle a click function you have to add an event to the document, instead of the element. A normal live click event code is like this

$("#element").live("click",function(){
  dosomething();
});

When using .on() to do the same task, the code will be like this :

$(document).on("click","#element",function(){
  dosomething();
});

Notice the big difference. Using .on() event have a lot more code than .live() and it’s not easy to use. It’s not comfortable. The motto of jQuery is Write Less, Do More. In the case of .on() the motto doesn’t apply. So we need .live() back. jQuery won’t bring it back. Hence we should take things on our own.

In this post I’m going to tell you How To Bring Back .live() function. It’s pretty simple. All you have to do is add some lines at a place of your jQuery file.

Open your jQuery source file and search for :

unbind:

You will get a code something like this :

unbind: function( types, fn ) {
  return this.off( types, null, fn );
},

If it’s a jQuery minified version, you will get something like this :

unbind:function(a,b){return this.off(a,null,b)},

Now add the following code just after the comma (,) of unbind :

live:function(types,data,fn){jQuery(document).on(types,this.selector,data,fn);return this;},die:function(types,data,fn){jQuery(document).off(types,this.selector);return this;},

And the whole code will be :

unbind:function(a,b){return this.off(a,null,b)},live:function(types,data,fn){jQuery(document).on(types,this.selector,data,fn);return this;},die:function(types,data,fn){jQuery(document).off(types,this.selector);return this;},

And on the unminified version :

unbind: function( types, fn ) {
  return this.off( types, null, fn );
},live:function(types,data,fn){jQuery(document).on(types,this.selector,data,fn);return this;},die:function(types,data,fn){jQuery(document).off(types,this.selector);return this;},

Now, try using .live() & .die() functions and it will work ! If you have any problems /suggestions /feedback, don’t hesitate to say it in the comments.