Reapply JS to dynamic generated content

1.2k Views Asked by At

What is the best way to reapply JS to dynamic generated content? I said "reapply JS" and not "rebind events" because a meant "reapply JS that bind events and also changes the dom", what I have done so far is something like this:

main.js:
function repplyDynamic(){
    $('.dynamic:not(.js-initialized)').each(function(){
        $(this).addClass('js-initialized').append('<div class="chaging_dom"></div>').click(function(){
            alert("Ae!");
        });
    });
}


other_code.js
$('body').append('<div id="dynamic">content</div>'); // could be a ajax call
reapplyDynamic();

But I think this is very messy. Do you guys have a better approach?

3

There are 3 best solutions below

1
Niet the Dark Absol On

Personally I have a function called dommods() that does all the modification I need (tooltips, forms, auto-sizing textareas, etc.) and call it after every nontrivial change to the DOM.

In other words, exactly what you're doing but with a different function name. Nothing wrong with it.

2
Maksym Kozlenko On

You can use jQuery's $().on method to attach event handlers to present or future HTML elements.

0
Joseph On
//main.js
function applyDynamicStuff(content){
    return content                                  //return content
        .append('<div class="chaging_dom"></div>')  //with appended element
        .click(function(){                          //with click hander
            alert("Ae!");
        });
}

//other_code.js 
var dynamicItem = $('<div>content</div>')           //the new content
applyDynamicStuff(dynamicItem).appendTo('body');    //apply Dynamic stuff and append to body