Skip to content Skip to sidebar Skip to footer

JQuery Switching Application From "live" To "on" Method

Possible Duplicate: jQuery 1.7 - Turning live() into on() Just switching my code from 'live' to 'on' and some events just don't fire any more, here is an example, can anyone pls

Solution 1:

You cannot replace live() with on() simply by changing the function name to on(); the signature changes as well.

$('selector').live('event', function () {

});

... becomes ....

$(document).on('event', 'selector', function () {

});

In it's current form, what you have is a direct replacement for bind() (of which click(), change() etc are aliases). As such, the handler is been bound directly to the element, rather than binding the handler to the document and taking advantage of event bubbling, which is what live() did.


Solution 2:

To use on() in the same manner as live(), do it as such:

$(document).on('click', 'a#doBulkLink', function() { } );

As indicated in the docs here: http://api.jquery.com/live/


Solution 3:

The way you have defined .on will not work if a#doBulkLink is inserted dynamically to the dom,

Try,

//replace document with any closest container of 'a#doBulkLink' which is available 
//in dom when this code is executed.

$(document).on ('click', 'a#doBulkLink', function () {
    createLabelsWithDestinationFolders();

    $('label.moveDocDestinationFolder').on('click', function (e) {

        doSomeAjaxStuffWithLabels();
        e.stopImmediatePropagation();  

    });

    e.preventDefault();

});

Solution 4:

I got it working, FIXED!!!!, I made 2 silly mistakes:

  • First event (on a#doBulkLink) is not dynamic (It was on the hidden element that exists on a page, and that#s what tricked me!)
  • In second event (on label.moveDocDestinationFolder) I used $('document') instead of $(document) in my JQuery ".on" method syntax,

So the code looks like this and it's working WELL in 100%:

// this is not dynamically added element, but still can use ".on" to attach an event to 
// outer div and delegate to a#doBulkLink when clicked
$('div#doBulkLinkBox').on('click', 'a#doBulkLink' ,function (e) {

    createLabelsWithDestinationFolders();

    // these are dynamic elements so let's use "on" to attach a click event
    $(document).on('click', 'label.moveDocDestinationFolder', function (e) { 
        doSomeAjaxFunkWithLabels();
        e.stopImmediatePropagation();  
    });

    e.preventDefault();
});

THANKS to everyone for tips!!


Post a Comment for "JQuery Switching Application From "live" To "on" Method"