So I'm currently using .append() to add a feature to all of the posts on a webpage, but when additional posts are loaded on the page, the appended features aren't included in the new content — I'm trying to come up with a way to make sure all of the new content has the appended feature too.
$(this).append('<div id="new_feature></div>');
Something like this?
$(this).live().append('<div id="new_feature></div>');
Maybe there's a way to make it constantly appending in a loop perhaps?
There is DOMNodeInserted event:
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('DOMNodeInserted','.inner',function() {
console.log(this);
});
update: this seems not works in IE, try propertychnage
event handler also ($('#appendme').on('DOMNodeInserted,propertychange'
) but i not sure, have no IE to check this right now.
update2: Domnode* seems deprecated according to mdn, they tell to use MutationObserver object instead
update3: seems here is no very crossbrowser solution for MutationEvents, see this answer, so my suggestion would be use code above, if event supported and fallback to setTimeOut
or livequery option.
update4:
If you depend only on .append()
you can patch jQuery.fn.append()
like this:
jQuery.fn.append=function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
$(elem).trigger('appended');
}
});
};
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('appended','.inner',function() {
console.log(this);
});
may be more correct is to spoof jQuery.fn.domManip
like here