Created
September 28, 2010 13:52
-
-
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
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
// 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); |
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
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
View working sample here: http://jsfiddle.net/mjangda/Mrpgs/