public
Last active — forked from cowboy/jquery.ba-domchanged.js

  • Download Gist
jquery.ba-domchanged.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
(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);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.