Search code examples
jquerymethodslive

jQuery - change from live() to on()


I have the following code and would like to change from using the live() method to using the on() method:

$('.commenttext').live('keydown', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

It is about commenting on a post - also one that was created created on the fly using the on() method. If I simply change only the word "live" to "on" like this

$('.commenttext').on('keydown', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

then it only works with items that weren't created on the fly.

UPDATE 1

I changed the code to the following:

$('.commentsDiv').on('keydown', '.commenttext', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

with commentsDiv being the parent element of commenttext, but still it doesn't work with elements that were created on the fly. For example, the following function creates the commentsDiv on the fly:

$('#postDiv').on('keydown', '#posttext', function(e) {
    if (e.which==13 && !e.shiftKey) {
        post($(this));
        return false;
    }
});

Does anyone know how to adjust properly?

Thanks :)


Solution

  • You need to attach the callback to a static parent of .commenttext static means exist on page load.

    Example:

    $('body').on('keydown', '.commenttext', function(e) {
        if ((e.which == 13) && !e.shiftKey) {
            comment($(this));
            return false;
        }
    });
    

    Or:

    $('{staticParentElement}').on('keydown', '.commenttext', function(e) {
        if ((e.which == 13) && !e.shiftKey) {
            comment($(this));
            return false;
        }
    });