jbutler483 jbutler483 - 11 months ago 95
Ajax Question

On create function in jquery

Having read this question, I found the answers outdated/depreciated and hence am asking if anyone would have any 'updated' answers to:

Does JQuery have a function call like

$('#myNewDivId').on('create', function(){


for a single div, or multiple 'appends':

$('.myNewDivWithClass').on('create', function(){


for a dynamically created div?

  • I would rather not include plugins (esp. 'outdated' ones like .livequery() plugin)

  • 'DOMSubtreeModified' seems to be depreciated, and so would there be an alternative?

  • I would need this function to be compatible with (at least) IE 10 + 11.

What I'm looking to do is on create of this 'new element', is to have an ajax call back to my controller to 'replace' this div with a partial view? However, without a jquery method to use, it seems more difficult than expected

Answer Source

There is no magic browser-solution that works for all older browsers although there are a few work-arounds using browser-specific features, but, if you are in control of the creation of the new elements, just broadcast a custom event on that new element (or its container) after adding it.


var newDiv = $('<div>', {id: myNewDivId});
newDiv.trigger('myname.loaded');      // trigger event on new element

and in the main JS listen for the event:

$(document).on('myname.loaded', function(e){
    // e.target is the element added
    $(e.target).css('color', 'red');

JSFiddle: http://jsfiddle.net/TrueBlueAussie/epg09n4d/3/

It is suggested below that you wrap this additional functionality in a function, but that assumes you will always use the append to add elements. Instead you could use a jQuery extension method:

e.g. add a modified method to jQuery

jQuery.fn.modified = function () {
    return this;

and call on the parent container (instead of the element):


JSFiddle: http://jsfiddle.net/TrueBlueAussie/epg09n4d/7/

Note: Targeting the container (not the added element(s)) would seem to be more useful and matches the pattern we used for Ajax updating of panels.