userlond
userlond

Reputation: 3824

Observer pattern in browser-javascript: subscribe to event "Dom element added" and handle this element

I have a query:

$(function() {
    $('form').each(function() {
      // do smthing with form
    });
});

Forms may appear dynamically, i.e. built by javascript. I need to handle them just after load, smth like:

$('form').onload(function() {
   // it's called after new form was added to dom
});

I thought about using setInterval, but maybe HTML5 or new ES standards brought smth new...

Does anybody help to compose on load callback with aforementioned characteristics?

P.S. To clarify the purpose: I need to attach event handler to event "element was added to dom".

Upvotes: 1

Views: 437

Answers (2)

Vahid Msm
Vahid Msm

Reputation: 1082

Actually there was an event which is deprecated by now called "DOMNodeInserted", it would be wise to use delegated events. with delegated events you can handle events on new elements that are dynamically add to DOM.

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Wrap it in a function

$(function() {
    function modForm() {
    $('form').each(function() {
      // do smthing with form
    });
    }
   modForm();
  $('a').click(function(){
    //add form dynamically
    $('body').append('<form>');
    //call the function agan
     modForm();
  });
});

Upvotes: 2

Related Questions