Skip to content

Instantly share code, notes, and snippets.

@josip
Created August 15, 2008 18:06
Show Gist options
  • Save josip/5613 to your computer and use it in GitHub Desktop.
Save josip/5613 to your computer and use it in GitHub Desktop.
(function ($) {
/** Watch for changes on CSS properties
* @param {String} property CSS attribute
* @param {String} id Watcher ID, used later for "un-watching"
* @param {Function} fn Function to get called when attribute changes. As first argument function receives new value, +this+ inside function refers to element.
* @returns {jQuery}
*/
$.fn.watch = function (property, id, fn) {
id += "Watcher";
return this
.data(id, {val: null, fn: watcher(property, id, fn)})
.bind("DOMAttrModified", this.data(id).fn);
};
/** Unwatch previously monitored CSS property on element
* @param {String} id Watcher's ID
* @returns {jQuery}
*/
$.fn.unwatch = function (id) {
id += "Watcher";
var _watcher = this.data(id);
if(!_watcher)
return this;
return this
.unbind("DOMAttrModified", _watcher.fn)
.removeData(id);
};
/** @ignore */
function watcher (property, id, fn) {
return function (event) {
if(this !== event.originalTarget || event.attrName !== "style")
return;
var $this = $(this),
new_val = $this.css(property),
data = $this.data(id);
if(!data)
return false;
if(new_val !== data.val)
return fn.call(this, data.val = new_val);
}
}
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment