Skip to content

Instantly share code, notes, and snippets.

@ralphholzmann
Forked from cowboy/jquery.ba-domchanged.js
Created April 25, 2010 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralphholzmann/378546 to your computer and use it in GitHub Desktop.
Save ralphholzmann/378546 to your computer and use it in GitHub Desktop.
(function($){
function domchanged(methods, type) {
$.each( methods.split(' '), function( i, method ) {
// Store a reference to the original method.
var orig = $.fn[ method ];
// Override the original method.
$.fn[ method ] = function(){
var args = arguments,
elems = [],
filtered = [];
// For each selected element...
if ( type == 'insertion' ) {
this.each(function(){
// Store the initial HTML.
var html = this.innerHTML;
// Execute the original method.
orig.apply( $(this), args );
// If the HTML has changed, add this element to the list of elements.
if ( this.innerHTML !== html ) {
elems.push( this );
}
})
} else {
this.each(function(){
// Store the initial HTML.
var parent = $(this).parent(),
html = parent[0].innerHTML;
// Execute the original method.
orig.apply( $(this), args );
// If the HTML has changed, add this element to the list of elements.
if ( parent[0].innerHTML !== html ) {
elems.push( parent[0] );
}
});
}
// Unique the elements list, and iterate over it. The goal here is, since
// the "domchanged" event will bubble, to remove any elements that are
// ancestors of other elements from the internal list.
$.each( $.unique( elems ), function( i, elem ){
var push = true;
filtered = $.map( filtered, function( item ){
if ( $.contains( elem, item ) ) {
// Since elem is an ancestor of filtered list item, discard elem.
push = false;
} else if ( $.contains( item, elem ) ) {
// Since elem is a descendant of filtered list item, replace item
// with elem.
push = false;
return elem;
}
});
// If elem wasn't discarded, push it onto the filtered items list.
push && filtered.push( elem );
});
// Trigger a custom 'domchanged' event that will bubble!
$(filtered).trigger({
'type' : 'domchanged',
'method' : method,
'manipulationType' : type
});
return this;
};
});
};
domchanged('unwrap html wrapAll wrapInner append appendTo html prepend prependTo text after before insertAfter insertBefore', 'insertion');
domchanged('detach empty remove unwrap', 'removal');
domchanged('replaceAll replaceWith', 'replacement');
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment