Skip to content

Instantly share code, notes, and snippets.

@rjungemann
Created February 23, 2010 19:39
Show Gist options
  • Save rjungemann/312609 to your computer and use it in GitHub Desktop.
Save rjungemann/312609 to your computer and use it in GitHub Desktop.
JQuery monitoring DOM properties
// Thanks to James Podolsey for this code, from the "Monitoring DOM
// Properties" article, located at
// http://james.padolsey.com/javascript/monitoring-dom-properties/
jQuery.fn.watch = function(id, fn) {
return this.each(function() {
var self = this, oldVal = self[id];
$(self).data('watch_timer',
setInterval(function() {
if(self[id] !== oldVal) {
fn.call(self, id, oldVal, self[id]);
oldVal = self[id];
}
}, 100);
);
});
return self;
};
jQuery.fn.unwatch = function(id) {
return this.each(function() {
clearInterval($(this).data('watch_timer'));
});
};
// // Usage:
//
// $('input').watch('value', function(propName, oldVal, newVal) {
// log('Value has been changed to ' + newVal);
// });
//
// // or...
//
// var obj = { prop: 123 };
// $(obj).watch('prop', function(propName, oldVal, newVal){
// log('Prop has been changed to ' + newVal);
// });
jQuery.fn.valuechange = function(fn) { return this.bind('valuechange', fn); };
jQuery.event.special.valuechange = {
setup: function() {
jQuery(this).watch('value', function() {
jQuery.event.handle.call(this, {type:'valuechange'});
});
},
teardown: function() { jQuery(this).unwatch('value'); }
};
// // Usage:
//
// $('input').bind('valuechange', function(){
// log('Value changed... New value: ' + this.value);
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment