jQuery: use .on() instead of .live() to attach event handler to $('selector') object

2.6k views Asked by At

I understand that .live() has been removed from jQuery 1.9 and that .on() should be used instead. So far .on() has worked perfectly for me if the selector is a string. For example,

$("a.offsite").live("click", function(){ alert("Goodbye!"); });

turned into

$(document).on("click", "a.offsite", function(){ alert("Goodbye!"); });

But how do I use .on() for a JQuery selector object (or a collection of objects) as follows?

var jele = $('.nav').find("a.offsite");
$(jele).live("click", function(){ alert("Goodbye!"); });

turned into

var jele = $('.nav').find("a.offsite");
$(document).on("click", jele, function(){ alert("Goodbye!"); });

Is the code above converted correctly? The problem I encounter is other event handlers bound to the same event yet different selector are also executed when the event fires. Hence I suspect this is not the correct way but I can't find any similar example in the official documentation.

I know I could have passed the selector string instead of the jele object into .on() method but in some cases I simply do not have access to the selector string, eg. when the jele object is passed as an argument into the function in which the binding occurs.

3

There are 3 answers

2
JordiVilaplana On

Once you've got the JQuery jele object, try to call the .on() function on jele:

$(jele).on("click", your-code-here);

Other way to do it is having the selector string of jele. Check out this post I found about retrieving the selector string of any JQuery object. Once you have the jele selector string, your code should be as follows:

$(document).on("click", selector, your-code-here);
1
saifur On
$(jele).on("click", function(){ alert("Goodbye!"); });
0
Yukulélé On

.on() replace .bind(), .live() and .delegate()

usage:

$('div').on('click',function(){/* ... */}); //equivalent to .bind()

this 3 lines are equivalent:

$('a','#menu').live('click',function(){/* ... */});
$('#menu').delegate('a','click',function(){/* ... */}); 
$('#menu').on('click','a',function(){/* ... */});