I am Cavic
I am Cavic

Reputation: 1085

jQuery working with elements added dynamically with no refresh

I have built an web app working on the interface now I am facing a challenge of working with elements that are added to the canvas dynamically from jQuery.

Eg.

$(document).ready(function(){
    //On Focus for textarea of Sheet
    $("textarea").focus(function(){
        $(this).css("height", "250px");
    });

    $("textarea").focusout(function (){
        $(this).css("height", "");
    });

});

Now this part works fine and it expands and shrinks my textarea as required. (ALL GOOD THERE!)

However this is very my problems occur, I have onclick that appends new textarea elements to the canvas.

Now I can't use .focus on those or .focusout for that matter. When I use .appendTo page doesn't refresh. (New elements are added with out refresh)

How can I get around this problem (correct way), I need my $("textarea").focus to be able to work with newly added elements.

Thanks!

Upvotes: 1

Views: 43

Answers (1)

Travis J
Travis J

Reputation: 82277

Bind them using delegates with jQuery's on.

$("body").on("focus","textarea",function(){
    $(this).css("height", "250px");
});

$("body").on("focusout","textarea",function (){
    $(this).css("height", "");
});

This will delegate the focus and focusout events to the matching selector ("textarea") when those events occur in the selector ("body"). If there is a closer element than body to select for the parent of this event delegation that is ideal, although not always possible depending on the dynamic nature of the page.

Upvotes: 2

Related Questions