-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsloth.max.js
79 lines (68 loc) · 1.77 KB
/
sloth.max.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
(function(context){
function sloth(){
//some private vars
var proto = 'prototype',
scroll = 'scroll',
slice = Array[proto].slice,
wTop,
wBottom,
undef,
delegate = context.setTimeout,
branches = [],
Branch = function(element, threshold, callback){
this.element = element;
this.threshold = threshold;
this.callback = function(){
callback(element);
};
},
execute = function(){
var i = branches.length,
branch;
if(i){
wTop = context.scrollY || context.pageYOffset;
wBottom = wTop + context.innerHeight;
while(i--){
branch = branches[i];
if (branch.visible()) {
delegate( branch.callback, 0 );
branches.splice(i, 1);
}
}
}else{
context.removeEventListener(scroll, execute);
}
};
Branch[proto].visible = function(){
var elem = this.element,
threshold = this.threshold,
top = elem.offsetTop - threshold,
bottom = top + elem.offsetHeight + threshold;
return wBottom >= top && wTop <= bottom;
};
//return Sloth function
return function(params){
if(params) {
var elements = params.on,
threshold = params.threshold !== undef ? params.threshold : 100,
callback = params.callback,
i;
if(!elements || !callback) throw 'elements or callback missing';
if(elements.length !== undef){
elements = slice.call(elements);
i = elements.length;
while(i--) branches.push(new Branch(elements[i], threshold, callback));
}else {
branches.push(new Branch(elements, threshold, callback))
}
execute();
branches.length && context.addEventListener(scroll, execute);
}
}
}
if(context.define && context.define.amd) {
context.define('sloth', sloth);
}else{
context.sloth = sloth();
}
})(this);