Search code examples
jquerytextarealive

How can I make this .live() in jQuery


I'm using jQuery plugin called charCount to display a character counter for some textareas, it works great, however when I add new text areas on the page (dinamically), the new text areas doesn't have the counter, I'm newbie, here is how I use the plugin:

$('.message-form').charCount({ allowed: 140, warning: 20 });

Update Solution:

$(".message-form").live("click", function(){
        if ($(this).data('hascharcount') == undefined) {
            $(this).data('hascharcount', true).charCount({ allowed: 140, warning: 20 });
        }
    });

Solution

  • The simplest way would just be to run that method on any new elements created.

    $('<textarea ...>').appendTo('#wherever').charCount({ allowed: 140, warning: 20 });
    

    But you asked about doing it using on() which means you don't want to do that.

    But

    $('.message-form').charCount({ allowed: 140, warning: 20 });
    

    can't simply be made to use on() as on() binds an event. Rather than edit a plugin which may have updates by the author at any time which would mean re-fiddling it, write around it.

    So, if you don't want to call .charCount each time after dynamically creating the elements, you can do this which will call it contextually (i.e. not until the user actually uses the element).

    $(document).on('focus', '.message-form', function(){
        if (typeof $(this).data('hascharcount')=='undefined') {
            $(this).data('hascharcount', true).charCount({ allowed: 140, warning: 20 });
        }
    })
    

    N.B. A lot of people assume .on() is an alias of the depreciated .live() which it isn't. To use on() as live(), i.e. for elements that don't exist at the time it's run, it needs something that already exists to anchor to such as the parent div that content is created inside of or, if you're lazy, document.