Create function in jquery
After reading this question , I found the answers outdated / deprecated and hence am asking if anyone has "updated" answers to:
Does jQuery have a function call like
$('#myNewDivId').on('create', function(){
});
for one div or multiple 'addends':
$('.myNewDivWithClass').on('create', function(){
});
for a dynamically created div?
- I would rather not include plugins (legacy for example) like the .livequery () plugin)
- "DOMSubtreeModified" seems to be depreciating, and is there an alternative?
- I need this feature for compatibility with (at least) IE 10 + 11.
What I want to do is create this "new element" to have an ajax call back to my controller to "replace" this div with a partial view? However, without using the jquery method, this seems more complicated than expected.
source to share
There is no magic browser solution that works for all old browsers, although there are a few workarounds using browser-specific functionality, but if you are in control of the creation of new elements, just send a custom event on that new element (or its container) after adding it ...
eg.
var newDiv = $('<div>', {id: myNewDivId});
$('#somewhere').append(newDiv);
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/
The following shows you add this additional functionality to a function, but it is assumed that you will always use append
to add items. You can use jQuery extension method instead:
eg. add method modified
to jQuery
jQuery.fn.modified = function () {
this.trigger('myname.loaded');
return this;
};
and call the parent container (instead of the element):
$('#somewhere').append(newDiv).modified();
JSFiddle: http://jsfiddle.net/TrueBlueAussie/epg09n4d/7/
Note. Targeting the container (rather than the added element (s)) seems to be more useful and follows the pattern we used to update the Ajax panels.
source to share