-
-
Save ralphholzmann/378546 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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