How to attach all events after manipulating the dom using ajax response. I have a ajax request which get a html response which is basically a fragment of html. that fragment HTML have many buttons. I want to refresh the dom so previously declared and attached events be applied into that fragment too. I dont want to keep on adding each events for each button using jquery on(). how else to do it?
-
possible duplicate of [jQuery event delegation](http://stackoverflow.com/questions/14679432/jquery-event-delegation) – Evan Trimboli Aug 24 '13 at 03:46
-
@EvanTrimboli - this question is not a dup of that one. The solution may be similar, but the question is not the same. – jfriend00 Aug 24 '13 at 03:52
-
Does there really need to be another answer explaining how event delegation works? – Evan Trimboli Aug 24 '13 at 03:55
-
3@EvanTrimboli - The way I understand it, you mark something a duplicate when it's the same question as is asked elsewhere. This is not the same question as what you proposed as a dup. Just because they both can be answered similarly does not mean they are duplicate questions. – jfriend00 Aug 24 '13 at 04:28
1 Answers
You can use delegated event handling which is set up ahead of time and can be made to apply to newly added DOM elements. Delegated event handling is done with .on()
and generally takes the form of:
$("static parent selector").on('click', 'selector for dynamic element', fn);
There is no clean way to just run your event installing code again and have it only apply to newly added DOM elements. You would have to put that code in a function and code it such that it never adds an event handler more than once and then you could call that function again after adding items to the DOM. Or, you could make the function take an argument for a parent object and only add event handlers in the newly added DOM hierarchy.
Here's another relevant answer about delegated event handling: Does jQuery.on() work for elements that are added after the event handler is created?