-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathjquery.mutationobserver.js
More file actions
48 lines (44 loc) · 1.64 KB
/
jquery.mutationobserver.js
File metadata and controls
48 lines (44 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* jQuery mutationObserver 1.0.4
* https://github.com/timbonicus/jquery-mutationobserver
*
* Dual licensed under the MIT and GPL licenses.
* http://en.wikipedia.org/wiki/MIT_License
* http://en.wikipedia.org/wiki/GNU_General_Public_License
*/
(function($) {
var jQueryMutationFns = ['after', 'append', 'before', 'empty', 'html', 'prepend', 'remove']
var mutationObservers = []
var __mutatedElements = []
var __mutationTimeout
$.each(jQueryMutationFns, function(i, fn) {
var originalFn = $.fn[fn]
$.fn[fn] = function() {
var me = this
var mutatedElement = (fn == 'remove') ? me.parent() : me
var result = originalFn.apply(this, arguments)
if (__mutatedElements.indexOf(mutatedElement) < 0)
__mutatedElements.push(mutatedElement)
clearTimeout(__mutationTimeout)
__mutationTimeout = setTimeout(function() {
fire()
__mutatedElements = []
}, 50)
return result
}
})
function fire() {
$.each(mutationObservers, function(i, observer) {
var hasMutatedChildren = __mutatedElements.some(function(el) { return $(el).closest(observer.el).length })
if (hasMutatedChildren)
observer.listener()
})
}
$.fn.mutationObserver = function(listenerFn) {
if (this.length == 0)
return this
if (this.length > 1)
return $.each(this, function(i, obj) { $(obj).mutationObserver(listenerFn) })
mutationObservers.push({el: this, listener: $.proxy(listenerFn, this)})
}
}(jQuery));