Reputation: 12431
I want to attach a focus event on dynamically created textarea
element. I have created a fiddle below which describes my problem. When I click on 'click' link another text area is created. It doesn't get focus event.
$("textarea").on("focus", function(){
alert("textarea focus");
$(this).blur();
});
$("a").click(function(){
$("div").append("<textarea>2</textarea>");
});
How can I add focus event on dynamic textarea? I want to avoid again attaching focus again and again for each new element
Upvotes: 0
Views: 7227
Reputation: 133453
Use Delegated events, as they have the advantage that they can process events from descendant elements that are added to the document at a later time.
As you are creating textarea dynamically.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
$("div").on("focus", "textarea", function(){
alert("textarea focus");
$(this).blur();
});
Upvotes: 1
Reputation: 82251
you shouild use event delegation.use:
$(document).on("focus","textarea", function(){
alert("textarea focus");
$(this).blur();
});
Upvotes: 1
Reputation: 38112
You need to use event delegation here since your textarea
is dynamically created:
$(document).on("focus","textarea", function(){
alert("textarea focus");
$(this).blur();
});
It will helps you to bind the focus
event on these newly added textarea
Upvotes: 3