Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently execute JavaScript functions when elements are inserted?

Initially, when the page loads, I search with jQuery for stuff like this:

<label for="first_name">name</label>
<input type="text" name="first_name" />

And change html to be fancier.

The problem becomes when I try to dynamically insert elements like these into DOM. Since nothing is binded to the newly created elements, I am not sure what's a proper way to run my "adjustement" functions. I wouldn't simply want to hack it and call adjust_html1(), adjust_html2(), etc manually right after inserting.

What is the most organized and efficient way to run code after html is inserted?

(sidenote: would be even cooler if there's a way to run it only on new html)

Edit: added a "for"

Edit 2: Here's my sample jQuery code that runs on document ready:

$('label').each(function() {
  /* do stuff */
});
like image 205
Jon Derring Avatar asked Feb 16 '26 08:02

Jon Derring


2 Answers

You could checkout the livequery plugin:

$('[name="first_name"]').livequery(function() {
    alert('A node with name=first_name was injected into the DOM');
    adjust(this);
});
like image 173
Darin Dimitrov Avatar answered Feb 17 '26 20:02

Darin Dimitrov


Use the live() binding method.

Attach a handler to the event for all elements which match the current selector, now and in the future.

like image 30
Jon Adams Avatar answered Feb 17 '26 21:02

Jon Adams