-
Notifications
You must be signed in to change notification settings - Fork 2
/
is-in-view.js
84 lines (72 loc) · 2.27 KB
/
is-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
78
79
80
81
82
83
84
const IsInView = {};
class Watcher {
constructor() {
this.elementsToWatch = [];
this.windowHeight = 0;
window.addEventListener('scroll', this.update.bind(this));
window.addEventListener('resize', this.resize.bind(this));
this.resize();
this.update();
}
update() {
this.elementsToWatch.forEach((elementBinding) => {
const { element, settings } = elementBinding;
const rect = element.getBoundingClientRect();
const elementHeight = rect.height;
const elementTopPosition = rect.top;
const elementBottomPosition = elementTopPosition + elementHeight;
if (
settings.showIfPartial
) {
if (
((elementTopPosition >= 0) && (elementTopPosition <= this.windowHeight)) ||
((elementBottomPosition >= 0) && (elementBottomPosition <= this.windowHeight))
) {
if (typeof settings.callback === 'function') settings.callback(element);
element.classList.add('is-partially-in-view');
element.classList.add('has-been-partially-in-view');
} else {
if (!element.classList.contains('is-partially-in-view')) return;
element.classList.remove('is-partially-in-view');
}
}
if (
(elementBottomPosition <= this.windowHeight) &&
(elementTopPosition <= this.windowHeight) &&
(elementBottomPosition >= 0) &&
(elementTopPosition >= 0)
) {
if (element.classList.contains('is-in-view')) return;
if (typeof settings.callback === 'function') settings.callback(element);
element.classList.add('is-in-view');
element.classList.add('has-been-fully-in-view');
} else {
if (!element.classList.contains('is-in-view')) return;
element.classList.remove('is-in-view');
}
});
}
resize() {
this.windowHeight = window.innerHeight;
this.update();
}
addElement(element, settings = {}) {
this.elementsToWatch.push({
element,
settings,
});
}
}
const watcher = new Watcher();
IsInView.install = (Vue) => {
Vue.directive('is-in-view', {
bind(el, binding) {
const { value } = binding;
watcher.addElement(el, value);
Vue.nextTick(() => {
watcher.update();
});
},
});
};
export default IsInView;