Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching events after DOM manipulation using JQuery ajax

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?

like image 273
varuog Avatar asked Aug 24 '13 03:08

varuog


People also ask

What is HTML DOM Events in JavaScript?

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.

How to add new elements using DOM manipulation methods in jQuery?

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.

What are AJAX events and how are they triggered?

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.

How do I assign events to HTML elements using JavaScript?

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:


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?

like image 55
jfriend00 Avatar answered Oct 06 '22 04:10

jfriend00