-
Notifications
You must be signed in to change notification settings - Fork 0
/
polyfill.in-view.js
77 lines (72 loc) · 1.91 KB
/
polyfill.in-view.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
var initInView = function() {
var rules;
var inView = function(selector) {
var inViewSelector = selector.match(/(.*):in-view/)[1];
var el = document.querySelectorAll(inViewSelector);
return el;
};
var getTargets = function(parent, selector) {
var el;
if (/:in-view$/g.test(selector)) {
el = [parent];
} else {
selector = selector.replace(/:in-view/, '');
el = parent.querySelectorAll(selector);
}
return el;
}
Polyfill({ selectors: [":in-view"] })
.doMatched( function(ruleDeclarations){
rules = ruleDeclarations;
window.addEventListener('scroll', applyRules);
})
.undoUnmatched( function(rules){
window.removeEventListener('scroll', applyRules);
});
var onscroll = function(e) {
rules.each(function(rule) {
inView(rule.getSelectors());
});
}
var applyRules = function() {
rules.each(function(rule) {
var targetSelector = rule.getSelectors();
var elements = inView(targetSelector);
var cssDeclarations = rule.getDeclaration();
for (var x in elements) {
if (elements.hasOwnProperty(x)) {
var el = elements[x];
if (
el.offsetTop < window.scrollY + window.innerHeight &&
el.offsetTop + el.offsetHeight > window.scrollY &&
el.offsetLeft + el.offsetWidth > 0 &&
el.offsetLeft < window.innerWidth
) {
var target = getTargets(el, targetSelector);
for (var y in target) {
if (target.hasOwnProperty(y)) {
for (var i in cssDeclarations) {
if (cssDeclarations.hasOwnProperty(i)) {
target[y].style[i] = cssDeclarations[i];
}
}
}
}
} else {
var target = getTargets(el, targetSelector);
for (var y in target) {
if (target.hasOwnProperty(y)) {
for (var i in cssDeclarations) {
if (cssDeclarations.hasOwnProperty(i)) {
target[y].style[i] = '';
}
}
}
}
}
}
}
});
}
};
initInView();