Skip to content

Instantly share code, notes, and snippets.

@mjangda
Created September 28, 2010 13:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjangda/601024 to your computer and use it in GitHub Desktop.
Save mjangda/601024 to your computer and use it in GitHub Desktop.
Adds a custom event to the default jQuery html event when the value is changed
// 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);
<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>
@mjangda
Copy link
Author

mjangda commented Sep 28, 2010

View working sample here: http://jsfiddle.net/mjangda/Mrpgs/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment