Adds a custom event to the default jQuery html event when the value is changed
<div id="hello">This is text!</div>
<script>
jQuery(document).ready(function() {
jQuery('#hello').bind('html-change-pre', function() {
console.log('html-change-pre triggered', this, arguments);
});
jQuery('#hello').bind('html-change-post', function() {
console.log('html-change-post triggered', this, arguments);
});
console.log('Calling html with 1 arg:');
jQuery('#hello').html('This is text (that has been changed)!');
console.log('Calling html with no args:');
console.log(jQuery('#hello').html());
});
</script>// Redefines jQuery.fn.html() 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 function
jQuery.fn.originalHtml = jQuery.fn.html;
// Let's redefine the html function to include a custom event
jQuery.fn.html = function() {
var currentHtml = this.originalHtml();
if(arguments.length) {
this.trigger(eventName + '-pre', jQuery.merge([currentHtml], arguments));
jQuery.fn.originalHtml.apply(this, arguments);
this.trigger(eventName + '-post', jQuery.merge([currentHtml], arguments));
return this;
} else {
return currentHtml;
}
}
})(jQuery);