Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Created July 16, 2016 22:36
Show Gist options
  • Save m3g4p0p/f72028927da3b12a2480e43f70bbfde5 to your computer and use it in GitHub Desktop.
Save m3g4p0p/f72028927da3b12a2480e43f70bbfde5 to your computer and use it in GitHub Desktop.
(function($) {
$.fn.watch = function(callback, once) {
var options = {
childList: true,
subtree: true
};
var _callOnNode = function() {
callback.call(this);
};
var _mutationHandler = function(mutations, observer) {
$.each(mutations, function() {
$.each(this.removedNodes, _callOnNode);
$.each(this.addedNodes, _callOnNode);
});
if (once) {
observer.disconnect();
}
};
$(this).each(function() {
var observer = new MutationObserver(_mutationHandler);
observer.observe(this, options);
});
return this;
};
})(window.jQuery);
@m3g4p0p
Copy link
Author

m3g4p0p commented Jul 16, 2016

jQuery watch

Watch an element for descendants to be be added or removed. Takes an event handler as argument where this refers to the element being added or removed, and optionally a boolean which can be set to true if changes should be observed only once (i.e. the handler will get disconnected after the first observed change).

Sample usage

$('body').watch(function() {
    $(this).addClass('dynamic-content');
}).append('<div/>');

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