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?
JavaScript HTML DOM Events. HTML DOM allows JavaScript to react to HTML events: Reacting to Events. A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
The following figure shows how the DOM manipulation methods add new elements. Let's have a quick overview of important DOM manipulation methods. The jQuery after () method inserts content (new or existing DOM elements) after target element (s) which is specified by a selector.
This is the full list of Ajax events, and in the order in which they are triggered. The indented events are triggered for each and every Ajax request (unless a global option has been set). The ajaxStart and ajaxStop events are events that relate to all Ajax requests together.
To assign events to HTML elements you can use event attributes. Assign an onclick event to a button element: In the example above, a function named displayDate will be executed when the button is clicked. The HTML DOM allows you to assign events to HTML elements using JavaScript: Assign an onclick event to a button element:
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With