This question already has an answer here:
- Turning live() into on() in jQuery 5 answers
My web framework automatically updated my jQuery script to the current last version, the 1.9.
Now all my:
$(".myclass").live("click", function() {...
don't work anymore. I mostly used it with some ajax called which filled html in my page.
I would know how to replace this functionnality in the last version. A friend told me to use "on" instead, but the "on" stays fixed on the same element.
Explanation, in this example (no ajax), I use a "+" icon, to display an "ul li list".
$(".closed").live('click', function(){
$("#ul_list_"+$(this).attr('id')).addClass("displayed").removeClass("hidden").show();
$(this).addClass("openned").removeClass('closed');
$(this).html('<i class="icon-minus"></i>');
});
$(".openned").live('click', function(){
$("#ul_list_"+$(this).attr('id')).addClass("hidden").removeClass("displayed").hide();
$(this).addClass("closed").removeClass('openned');
$(this).html('<i class="icon-plus"></i>');
});
(I know that the script is not the most optimized ever, but it worked. I used classes to open or close my lists. And if the visitor doesn't have JS enabled, nothing is hidden, all the folded lists are opened)
Notes:
- I've tried https://github.com/jquery/jquery-migrate, but the only message that I have is "JQMIGRATE: jQuery.fn.live() is deprecated", not how to fix it.
The docs already provide an example:
So:
$(document).on("click", ".closed", function() { ... })
.You need to use
on
with a delegated handler:Note that you should replace
#parent
with the closest parent element to.closed
which is available on page load - usually the element which.closed
was appended to.you have to use the
on
instead oflive
. because live is deprecated on the version 1.7