1

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?

Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55
lucaswxp
  • 2,031
  • 5
  • 23
  • 34

3 Answers3

1

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Yes, but I wanted something more organized, that I don't need to specify if an element was already "initialize" with a class/data. Maybe a plugin? – lucaswxp May 10 '12 at 01:29
0

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

Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55
  • This solves it if I only needed to reattach events. But I also need to change the DOM. – lucaswxp May 10 '12 at 01:05
  • Check this one: http://stackoverflow.com/questions/7692730/dom-mutation-event-in-jquery-or-vanilla-javascript - it shows several methods to monitor DOM changes with jQuery – Maksym Kozlenko May 10 '12 at 04:03
0
//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
Joseph
  • 117,725
  • 30
  • 181
  • 234