<table>
<tr>
<td valign="top">
<button id="html">Click to see change 'html'.</button><br/>
<button id="append">Click to see change 'append'.</button><br/>
<button id="prepend">Click to see change 'prepend'.</button><br/>
<div id="hello">This is text!</div>
</td>
<td valign="top">
<div id="console"></div>
</td>
</tr>
</table>
JavaScript
// Redefines $.fn.html(), $.fn.append(), $.fn.prepend() to add custom events that are triggered before and after a DOM element's innerHtml is changed
// html-change-pre is triggered before the innerHtml is changed
// html-change-post is triggered after the innerHtml is changed
(function($) {
var eventName = 'html-change';
// Save a reference to the original html, append and prepend function
$.fn.htmlx = $.fn.html;
$.fn.appendx = $.fn.append;
$.fn.prependx = $.fn.prepend;
// Let's redefine the html, append and prepend function to include a custom event
$.fn.html = function() {
var currentHtml = this.htmlx();
if(arguments.length) {
this.trigger(eventName + '-pre', jQuery.merge([currentHtml], arguments));
jQuery.fn.htmlx.apply(this, arguments);
this.trigger(eventName + '-post', jQuery.merge([currentHtml], arguments));
return this;
} else {
return currentHtml;
}
}
$.fn.append = function() {
var currentHtml = this.htmlx();
if(arguments.length) {
this.trigger(eventName + '-pre', jQuery.merge([currentHtml], arguments));
jQuery.fn.appendx.apply(this, arguments);
this.trigger(eventName + '-post', jQuery.merge([currentHtml], arguments));
return this;
} else {
return currentHtml;
}
}
$.fn.prepend = function() {
var currentHtml = this.htmlx();
if(arguments.length) {
this.trigger(eventName + '-pre', jQuery.merge([currentHtml], arguments));
jQuery.fn.prependx.apply(this, arguments);
this.trigger(eventName + '-post', jQuery.merge([currentHtml], arguments));
return this;
} else {
return currentHtml;
}
}
})(jQuery);
// Test
jQuery(document).ready(function() {
jQuery('#hello').bind('html-change-pre', function() {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.