Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace "live" from jQuery 1.8.3 to jQuery 1.9? [duplicate]

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.
like image 769
Polopollo Avatar asked Jan 23 '13 12:01

Polopollo


People also ask

What is jQuery 1. 9 1?

jquery is a package that makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

What is .live in jQuery?

jQuery | live() MethodThis method is used to attach one or more event handlers for the selected elements. It also specifies the function that runs when the event occurs. The event handlers used will work for both current and future elements matching the selector.


1 Answers

The docs already provide an example:

Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+

So: $(document).on("click", ".closed", function() { ... }).

like image 118
Jon Avatar answered Oct 27 '22 18:10

Jon