This repository has been archived by the owner on Jan 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.js
62 lines (50 loc) · 1.6 KB
/
source.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
import 'core-js/modules/es6.object.assign';
import 'core-js/modules/es6.array.from';
export default class Parallax {
constructor(selector, options) {
this.lastPosition = -1;
// Establish default settings
this.settings = Object.assign({
speed: 0.2,
prefix: false,
}, options);
if (typeof selector === 'string') {
this.elems = Array.from(document.querySelectorAll(selector));
} else if (Array.isArray(selector)) {
this.elems = selector;
} else {
this.elems = [selector];
}
}
updatePosition() {
this.elems.forEach((elem) => {
const offset = elem.getBoundingClientRect().top + this.lastPosition;
const yPosition = Math.round((offset - this.lastPosition) * this.settings.speed);
// Apply the y-axis transform
elem.style.transform = `translate3d(0, ${yPosition * -1}px, 0)`; // eslint-disable-line
if (this.settings.prefix) {
this.setVendorStyle(elem, 'Transform', `translate3d(0, ${yPosition * -1}px, 0)`);
}
});
}
animate() {
// If the offset position hasn't changed, skip this frame
if (this.lastPosition === window.pageYOffset) {
window.requestAnimationFrame(() => {
this.animate();
});
return false;
}
// Save the new offset position
this.lastPosition = window.pageYOffset;
this.updatePosition();
return window.requestAnimationFrame(() => {
this.animate();
});
}
setVendorStyle(elem, prop, value) {
['webkit', 'moz', 'ms', 'o'].forEach((prefix) => {
elem.style[`${prefix}${prop}`] = value; // eslint-disable-line
});
}
}