forked from dixonandmoe/rellax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrellax.js
243 lines (196 loc) · 7.43 KB
/
rellax.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// ------------------------------------------
// Rellax.js - v1.0.0
// Buttery smooth parallax library
// Copyright (c) 2016 Moe Amaya (@moeamaya)
// MIT license
//
// Thanks to Paraxify.js and Jaime Cabllero
// for parallax concepts
// ------------------------------------------
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.Rellax = factory();
}
}(this, function () {
var Rellax = function(el, options){
"use strict";
var self = Object.create(Rellax.prototype);
var posY = 0; // set it to -1 so the animate function gets called at least once
var screenY = 0;
var blocks = [];
var pause = false;
// check what requestAnimationFrame to use, and if
// it's not supported, use the onscroll event
var loop = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(callback){ setTimeout(callback, 1000 / 60); };
// limit the given number in the range [min, max]
var clamp = function(num, min, max) {
return (num <= min) ? min : ((num >= max) ? max : num);
};
// Default Settings
self.options = {
speed: -2,
center: false
};
// User defined options (might have more in the future)
if (options){
Object.keys(options).forEach(function(key){
self.options[key] = options[key];
});
}
// If some clown tries to crank speed, limit them to +-10
self.options.speed = clamp(self.options.speed, -10, 10);
// By default, rellax class
if (!el) {
el = '.rellax';
}
// Classes
if (document.getElementsByClassName(el.replace('.',''))){
self.elems = document.getElementsByClassName(el.replace('.',''));
}
// Now query selector
else if (document.querySelector(el) !== false) {
self.elems = document.querySelector(el);
}
// The elements don't exist
else {
throw new Error("The elements you're trying to select don't exist.");
}
// Let's kick this script off
// Build array for cached element values
// Bind scroll and resize to animate method
var init = function() {
screenY = window.innerHeight;
setPosition();
// Get and cache initial position of all elements
for (var i = 0; i < self.elems.length; i++){
var block = createBlock(self.elems[i]);
blocks.push(block);
}
window.addEventListener('resize', function(){
animate();
});
// Start the loop
update();
// The loop does nothing if the scrollPosition did not change
// so call animate to make sure every element has their transforms
animate();
};
// We want to cache the parallax blocks'
// values: base, top, height, speed
// el: is dom object, return: el cache values
var createBlock = function(el) {
var dataPercentage = el.getAttribute('data-rellax-percentage');
var dataSpeed = el.getAttribute('data-rellax-speed');
// initializing at scrollY = 0 (top of browser)
// ensures elements are positioned based on HTML layout.
//
// If the element has the percentage attribute, the posY needs to be
// the current scroll position's value, so that the elements are still positioned based on HTML layout
var posY = dataPercentage || self.options.center ? document.body.scrollTop : 0;
var blockTop = posY + el.getBoundingClientRect().top;
var blockHeight = el.clientHeight || el.offsetHeight || el.scrollHeight;
// apparently parallax equation everyone uses
var percentage = dataPercentage ? dataPercentage : (posY - blockTop + screenY) / (blockHeight + screenY);
if(self.options.center){ percentage = 0.5; }
// Optional individual block speed as data attr, otherwise global speed
// Check if has percentage attr, and limit speed to 5, else limit it to 10
var speed = dataSpeed ? clamp(dataSpeed, -10, 10) : self.options.speed;
if (dataPercentage || self.options.center) {
speed = clamp(dataSpeed || self.options.speed, -5, 5);
}
var base = updatePosition(percentage, speed);
// ~~Store non-translate3d transforms~~
// Store inline styles and extract transforms
var style = el.style.cssText;
var transform = '';
// Check if there's an inline styled transform
if (style.indexOf('transform') >= 0) {
// Get the index of the transform
var index = style.indexOf('transform');
// Trim the style to the transform point and get the following semi-colon index
var trimmedStyle = style.slice(index);
var delimiter = trimmedStyle.indexOf(';');
// Remove "transform" string and save the attribute
if (delimiter) {
transform = " " + trimmedStyle.slice(11, delimiter).replace(/\s/g,'');
} else {
transform = " " + trimmedStyle.slice(11).replace(/\s/g,'');
}
}
return {
base: base,
top: blockTop,
height: blockHeight,
speed: speed,
style: style,
transform: transform
};
};
// set scroll position (posY)
// side effect method is not ideal, but okay for now
// returns true if the scroll changed, false if nothing happened
var setPosition = function() {
var oldY = posY;
if (window.pageYOffset !== undefined) {
posY = window.pageYOffset;
} else {
posY = (document.documentElement || document.body.parentNode || document.body).scrollTop;
}
if (oldY != posY) {
// scroll changed, return true
return true;
}
// scroll did not change
return false;
};
// Ahh a pure function, gets new transform value
// based on scrollPostion and speed
var updatePosition = function(percentage, speed) {
var value = (speed * (100 * (1 - percentage)));
return Math.round(value);
};
//
var update = function() {
if (setPosition() && pause === false) {
animate();
}
// loop again
loop(update);
};
// Transform3d on parallax element
var animate = function() {
for (var i = 0; i < self.elems.length; i++){
var percentage = ((posY - blocks[i].top + screenY) / (blocks[i].height + screenY));
// Subtracting initialize value, so element stays in same spot as HTML
var position = updatePosition(percentage, blocks[i].speed) - blocks[i].base;
// Move that element
// (Prepare the new transform and append initial inline transforms. Set the new, and preppend previous inline styles)
var translate = ' translate3d(0,' + position + 'px' + ',0)' + blocks[i].transform;
self.elems[i].style.cssText = blocks[i].style+'-webkit-transform:'+translate+';-moz-transform:'+translate+';transform:'+translate+';';
}
};
self.destroy = function() {
for (var i = 0; i < self.elems.length; i++){
self.elems[i].style.cssText = blocks[i].style;
}
pause = true;
};
init();
return self;
};
return Rellax;
}));