jquery.parallax.min.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. //============================================================
  2. //
  3. // The MIT License
  4. //
  5. // Copyright (C) 2014 Matthew Wagerfield - @wagerfield
  6. //
  7. // Permission is hereby granted, free of charge, to any
  8. // person obtaining a copy of this software and associated
  9. // documentation files (the "Software"), to deal in the
  10. // Software without restriction, including without limitation
  11. // the rights to use, copy, modify, merge, publish, distribute,
  12. // sublicense, and/or sell copies of the Software, and to
  13. // permit persons to whom the Software is furnished to do
  14. // so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice
  17. // shall be included in all copies or substantial portions
  18. // of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
  21. // OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
  22. // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  23. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
  24. // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  25. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
  26. // AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  27. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
  28. // OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. //============================================================
  31. /**
  32. * jQuery || Zepto Parallax Plugin
  33. * @author Matthew Wagerfield - @wagerfield
  34. * @description Creates a parallax effect between an array of layers,
  35. * driving the motion from the gyroscope output of a smartdevice.
  36. * If no gyroscope is available, the cursor position is used.
  37. */
  38. ;(function($, window, document, undefined) {
  39. // Strict Mode
  40. 'use strict';
  41. // Constants
  42. var NAME = 'parallax';
  43. var MAGIC_NUMBER = 30;
  44. var DEFAULTS = {
  45. relativeInput: false,
  46. clipRelativeInput: false,
  47. calibrationThreshold: 100,
  48. calibrationDelay: 500,
  49. supportDelay: 500,
  50. calibrateX: false,
  51. calibrateY: true,
  52. invertX: true,
  53. invertY: true,
  54. limitX: false,
  55. limitY: false,
  56. scalarX: 10.0,
  57. scalarY: 10.0,
  58. frictionX: 0.1,
  59. frictionY: 0.1,
  60. originX: 0.5,
  61. originY: 0.5
  62. };
  63. function Plugin(element, options) {
  64. // DOM Context
  65. this.element = element;
  66. // Selections
  67. this.$context = $(element).data('api', this);
  68. this.$layers = this.$context.find('.layer');
  69. // Data Extraction
  70. var data = {
  71. calibrateX: this.$context.data('calibrate-x') || null,
  72. calibrateY: this.$context.data('calibrate-y') || null,
  73. invertX: this.$context.data('invert-x') || null,
  74. invertY: this.$context.data('invert-y') || null,
  75. limitX: parseFloat(this.$context.data('limit-x')) || null,
  76. limitY: parseFloat(this.$context.data('limit-y')) || null,
  77. scalarX: parseFloat(this.$context.data('scalar-x')) || null,
  78. scalarY: parseFloat(this.$context.data('scalar-y')) || null,
  79. frictionX: parseFloat(this.$context.data('friction-x')) || null,
  80. frictionY: parseFloat(this.$context.data('friction-y')) || null,
  81. originX: parseFloat(this.$context.data('origin-x')) || null,
  82. originY: parseFloat(this.$context.data('origin-y')) || null
  83. };
  84. // Delete Null Data Values
  85. for (var key in data) {
  86. if (data[key] === null) delete data[key];
  87. }
  88. // Compose Settings Object
  89. $.extend(this, DEFAULTS, options, data);
  90. // States
  91. this.calibrationTimer = null;
  92. this.calibrationFlag = true;
  93. this.enabled = false;
  94. this.depths = [];
  95. this.raf = null;
  96. // Element Bounds
  97. this.bounds = null;
  98. this.ex = 0;
  99. this.ey = 0;
  100. this.ew = 0;
  101. this.eh = 0;
  102. // Element Center
  103. this.ecx = 0;
  104. this.ecy = 0;
  105. // Element Range
  106. this.erx = 0;
  107. this.ery = 0;
  108. // Calibration
  109. this.cx = 0;
  110. this.cy = 0;
  111. // Input
  112. this.ix = 0;
  113. this.iy = 0;
  114. // Motion
  115. this.mx = 0;
  116. this.my = 0;
  117. // Velocity
  118. this.vx = 0;
  119. this.vy = 0;
  120. // Callbacks
  121. this.onMouseMove = this.onMouseMove.bind(this);
  122. this.onDeviceOrientation = this.onDeviceOrientation.bind(this);
  123. this.onOrientationTimer = this.onOrientationTimer.bind(this);
  124. this.onCalibrationTimer = this.onCalibrationTimer.bind(this);
  125. this.onAnimationFrame = this.onAnimationFrame.bind(this);
  126. this.onWindowResize = this.onWindowResize.bind(this);
  127. // Initialise
  128. this.initialise();
  129. }
  130. Plugin.prototype.transformSupport = function(value) {
  131. var element = document.createElement('div');
  132. var propertySupport = false;
  133. var propertyValue = null;
  134. var featureSupport = false;
  135. var cssProperty = null;
  136. var jsProperty = null;
  137. for (var i = 0, l = this.vendors.length; i < l; i++) {
  138. if (this.vendors[i] !== null) {
  139. cssProperty = this.vendors[i][0] + 'transform';
  140. jsProperty = this.vendors[i][1] + 'Transform';
  141. } else {
  142. cssProperty = 'transform';
  143. jsProperty = 'transform';
  144. }
  145. if (element.style[jsProperty] !== undefined) {
  146. propertySupport = true;
  147. break;
  148. }
  149. }
  150. switch(value) {
  151. case '2D':
  152. featureSupport = propertySupport;
  153. break;
  154. case '3D':
  155. if (propertySupport) {
  156. var body = document.body || document.createElement('body');
  157. var documentElement = document.documentElement;
  158. var documentOverflow = documentElement.style.overflow;
  159. if (!document.body) {
  160. documentElement.appendChild(body);
  161. }
  162. body.appendChild(element);
  163. element.style[jsProperty] = 'translate3d(1px,1px,1px)';
  164. propertyValue = window.getComputedStyle(element).getPropertyValue(cssProperty);
  165. featureSupport = propertyValue !== undefined && propertyValue.length > 0 && propertyValue !== "none";
  166. documentElement.style.overflow = documentOverflow;
  167. body.removeChild(element);
  168. }
  169. break;
  170. }
  171. return featureSupport;
  172. };
  173. Plugin.prototype.ww = null;
  174. Plugin.prototype.wh = null;
  175. Plugin.prototype.wcx = null;
  176. Plugin.prototype.wcy = null;
  177. Plugin.prototype.wrx = null;
  178. Plugin.prototype.wry = null;
  179. Plugin.prototype.portrait = null;
  180. Plugin.prototype.desktop = !navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|BB10|mobi|tablet|opera mini|nexus 7)/i);
  181. Plugin.prototype.vendors = [null,['-webkit-','webkit'],['-moz-','Moz'],['-o-','O'],['-ms-','ms']];
  182. Plugin.prototype.motionSupport = !!window.DeviceMotionEvent;
  183. Plugin.prototype.orientationSupport = !!window.DeviceOrientationEvent;
  184. Plugin.prototype.orientationStatus = 0;
  185. Plugin.prototype.transform2DSupport = Plugin.prototype.transformSupport('2D');
  186. Plugin.prototype.transform3DSupport = Plugin.prototype.transformSupport('3D');
  187. Plugin.prototype.propertyCache = {};
  188. Plugin.prototype.initialise = function() {
  189. // Configure Styles
  190. if (this.$context.css('position') === 'static') {
  191. this.$context.css({
  192. position:'relative'
  193. });
  194. }
  195. // Hardware Accelerate Context
  196. this.accelerate(this.$context);
  197. // Setup
  198. this.updateLayers();
  199. this.updateDimensions();
  200. this.enable();
  201. this.queueCalibration(this.calibrationDelay);
  202. };
  203. Plugin.prototype.updateLayers = function() {
  204. // Cache Layer Elements
  205. this.$layers = this.$context.find('.layer');
  206. this.depths = [];
  207. // Configure Layer Styles
  208. this.$layers.css({
  209. position:'absolute',
  210. display:'block',
  211. left: 0,
  212. top: 0
  213. });
  214. this.$layers.first().css({
  215. position:'relative'
  216. });
  217. // Hardware Accelerate Layers
  218. this.accelerate(this.$layers);
  219. // Cache Depths
  220. this.$layers.each($.proxy(function(index, element) {
  221. this.depths.push($(element).data('depth') || 0);
  222. }, this));
  223. };
  224. Plugin.prototype.updateDimensions = function() {
  225. this.ww = window.innerWidth;
  226. this.wh = window.innerHeight;
  227. this.wcx = this.ww * this.originX;
  228. this.wcy = this.wh * this.originY;
  229. this.wrx = Math.max(this.wcx, this.ww - this.wcx);
  230. this.wry = Math.max(this.wcy, this.wh - this.wcy);
  231. };
  232. Plugin.prototype.updateBounds = function() {
  233. this.bounds = this.element.getBoundingClientRect();
  234. this.ex = this.bounds.left;
  235. this.ey = this.bounds.top;
  236. this.ew = this.bounds.width;
  237. this.eh = this.bounds.height;
  238. this.ecx = this.ew * this.originX;
  239. this.ecy = this.eh * this.originY;
  240. this.erx = Math.max(this.ecx, this.ew - this.ecx);
  241. this.ery = Math.max(this.ecy, this.eh - this.ecy);
  242. };
  243. Plugin.prototype.queueCalibration = function(delay) {
  244. clearTimeout(this.calibrationTimer);
  245. this.calibrationTimer = setTimeout(this.onCalibrationTimer, delay);
  246. };
  247. Plugin.prototype.enable = function() {
  248. if (!this.enabled) {
  249. this.enabled = true;
  250. if (this.orientationSupport) {
  251. this.portrait = null;
  252. window.addEventListener('deviceorientation', this.onDeviceOrientation);
  253. setTimeout(this.onOrientationTimer, this.supportDelay);
  254. } else {
  255. this.cx = 0;
  256. this.cy = 0;
  257. this.portrait = false;
  258. window.addEventListener('mousemove', this.onMouseMove);
  259. }
  260. window.addEventListener('resize', this.onWindowResize);
  261. this.raf = requestAnimationFrame(this.onAnimationFrame);
  262. }
  263. };
  264. Plugin.prototype.disable = function() {
  265. if (this.enabled) {
  266. this.enabled = false;
  267. if (this.orientationSupport) {
  268. window.removeEventListener('deviceorientation', this.onDeviceOrientation);
  269. } else {
  270. window.removeEventListener('mousemove', this.onMouseMove);
  271. }
  272. window.removeEventListener('resize', this.onWindowResize);
  273. cancelAnimationFrame(this.raf);
  274. }
  275. };
  276. Plugin.prototype.calibrate = function(x, y) {
  277. this.calibrateX = x === undefined ? this.calibrateX : x;
  278. this.calibrateY = y === undefined ? this.calibrateY : y;
  279. };
  280. Plugin.prototype.invert = function(x, y) {
  281. this.invertX = x === undefined ? this.invertX : x;
  282. this.invertY = y === undefined ? this.invertY : y;
  283. };
  284. Plugin.prototype.friction = function(x, y) {
  285. this.frictionX = x === undefined ? this.frictionX : x;
  286. this.frictionY = y === undefined ? this.frictionY : y;
  287. };
  288. Plugin.prototype.scalar = function(x, y) {
  289. this.scalarX = x === undefined ? this.scalarX : x;
  290. this.scalarY = y === undefined ? this.scalarY : y;
  291. };
  292. Plugin.prototype.limit = function(x, y) {
  293. this.limitX = x === undefined ? this.limitX : x;
  294. this.limitY = y === undefined ? this.limitY : y;
  295. };
  296. Plugin.prototype.origin = function(x, y) {
  297. this.originX = x === undefined ? this.originX : x;
  298. this.originY = y === undefined ? this.originY : y;
  299. };
  300. Plugin.prototype.clamp = function(value, min, max) {
  301. value = Math.max(value, min);
  302. value = Math.min(value, max);
  303. return value;
  304. };
  305. Plugin.prototype.css = function(element, property, value) {
  306. var jsProperty = this.propertyCache[property];
  307. if (!jsProperty) {
  308. for (var i = 0, l = this.vendors.length; i < l; i++) {
  309. if (this.vendors[i] !== null) {
  310. jsProperty = $.camelCase(this.vendors[i][1] + '-' + property);
  311. } else {
  312. jsProperty = property;
  313. }
  314. if (element.style[jsProperty] !== undefined) {
  315. this.propertyCache[property] = jsProperty;
  316. break;
  317. }
  318. }
  319. }
  320. element.style[jsProperty] = value;
  321. };
  322. Plugin.prototype.accelerate = function($element) {
  323. for (var i = 0, l = $element.length; i < l; i++) {
  324. var element = $element[i];
  325. this.css(element, 'transform', 'translate3d(0,0,0)');
  326. this.css(element, 'transform-style', 'preserve-3d');
  327. this.css(element, 'backface-visibility', 'hidden');
  328. }
  329. };
  330. Plugin.prototype.setPosition = function(element, x, y) {
  331. x += 'px';
  332. y += 'px';
  333. if (this.transform3DSupport) {
  334. this.css(element, 'transform', 'translate3d('+x+','+y+',0)');
  335. } else if (this.transform2DSupport) {
  336. this.css(element, 'transform', 'translate('+x+','+y+')');
  337. } else {
  338. element.style.left = x;
  339. element.style.top = y;
  340. }
  341. };
  342. Plugin.prototype.onOrientationTimer = function(event) {
  343. if (this.orientationSupport && this.orientationStatus === 0) {
  344. this.disable();
  345. this.orientationSupport = false;
  346. this.enable();
  347. }
  348. };
  349. Plugin.prototype.onCalibrationTimer = function(event) {
  350. this.calibrationFlag = true;
  351. };
  352. Plugin.prototype.onWindowResize = function(event) {
  353. this.updateDimensions();
  354. };
  355. Plugin.prototype.onAnimationFrame = function() {
  356. this.updateBounds();
  357. var dx = this.ix - this.cx;
  358. var dy = this.iy - this.cy;
  359. if ((Math.abs(dx) > this.calibrationThreshold) || (Math.abs(dy) > this.calibrationThreshold)) {
  360. this.queueCalibration(0);
  361. }
  362. if (this.portrait) {
  363. this.mx = this.calibrateX ? dy : this.iy;
  364. this.my = this.calibrateY ? dx : this.ix;
  365. } else {
  366. this.mx = this.calibrateX ? dx : this.ix;
  367. this.my = this.calibrateY ? dy : this.iy;
  368. }
  369. this.mx *= this.ew * (this.scalarX / 100);
  370. this.my *= this.eh * (this.scalarY / 100);
  371. if (!isNaN(parseFloat(this.limitX))) {
  372. this.mx = this.clamp(this.mx, -this.limitX, this.limitX);
  373. }
  374. if (!isNaN(parseFloat(this.limitY))) {
  375. this.my = this.clamp(this.my, -this.limitY, this.limitY);
  376. }
  377. this.vx += (this.mx - this.vx) * this.frictionX;
  378. this.vy += (this.my - this.vy) * this.frictionY;
  379. for (var i = 0, l = this.$layers.length; i < l; i++) {
  380. var depth = this.depths[i];
  381. var layer = this.$layers[i];
  382. var xOffset = this.vx * depth * (this.invertX ? -1 : 1);
  383. var yOffset = this.vy * depth * (this.invertY ? -1 : 1);
  384. this.setPosition(layer, xOffset, yOffset);
  385. }
  386. this.raf = requestAnimationFrame(this.onAnimationFrame);
  387. };
  388. Plugin.prototype.onDeviceOrientation = function(event) {
  389. // Validate environment and event properties.
  390. if (!this.desktop && event.beta !== null && event.gamma !== null) {
  391. // Set orientation status.
  392. this.orientationStatus = 1;
  393. // Extract Rotation
  394. var x = (event.beta || 0) / MAGIC_NUMBER; // -90 :: 90
  395. var y = (event.gamma || 0) / MAGIC_NUMBER; // -180 :: 180
  396. // Detect Orientation Change
  397. var portrait = window.innerHeight > window.innerWidth;
  398. if (this.portrait !== portrait) {
  399. this.portrait = portrait;
  400. this.calibrationFlag = true;
  401. }
  402. // Set Calibration
  403. if (this.calibrationFlag) {
  404. this.calibrationFlag = false;
  405. this.cx = x;
  406. this.cy = y;
  407. }
  408. // Set Input
  409. this.ix = x;
  410. this.iy = y;
  411. }
  412. };
  413. Plugin.prototype.onMouseMove = function(event) {
  414. // Cache mouse coordinates.
  415. var clientX = event.clientX;
  416. var clientY = event.clientY;
  417. // Calculate Mouse Input
  418. if (!this.orientationSupport && this.relativeInput) {
  419. // Clip mouse coordinates inside element bounds.
  420. if (this.clipRelativeInput) {
  421. clientX = Math.max(clientX, this.ex);
  422. clientX = Math.min(clientX, this.ex + this.ew);
  423. clientY = Math.max(clientY, this.ey);
  424. clientY = Math.min(clientY, this.ey + this.eh);
  425. }
  426. // Calculate input relative to the element.
  427. this.ix = (clientX - this.ex - this.ecx) / this.erx;
  428. this.iy = (clientY - this.ey - this.ecy) / this.ery;
  429. } else {
  430. // Calculate input relative to the window.
  431. this.ix = (clientX - this.wcx) / this.wrx;
  432. this.iy = (clientY - this.wcy) / this.wry;
  433. }
  434. };
  435. var API = {
  436. enable: Plugin.prototype.enable,
  437. disable: Plugin.prototype.disable,
  438. updateLayers: Plugin.prototype.updateLayers,
  439. calibrate: Plugin.prototype.calibrate,
  440. friction: Plugin.prototype.friction,
  441. invert: Plugin.prototype.invert,
  442. scalar: Plugin.prototype.scalar,
  443. limit: Plugin.prototype.limit,
  444. origin: Plugin.prototype.origin
  445. };
  446. $.fn[NAME] = function (value) {
  447. var args = arguments;
  448. return this.each(function () {
  449. var $this = $(this);
  450. var plugin = $this.data(NAME);
  451. if (!plugin) {
  452. plugin = new Plugin(this, value);
  453. $this.data(NAME, plugin);
  454. }
  455. if (API[value]) {
  456. plugin[value].apply(plugin, Array.prototype.slice.call(args, 1));
  457. }
  458. });
  459. };
  460. })(window.jQuery || window.Zepto, window, document);
  461. /**
  462. * Request Animation Frame Polyfill.
  463. * @author Tino Zijdel
  464. * @author Paul Irish
  465. * @see https://gist.github.com/paulirish/1579671
  466. */
  467. ;(function() {
  468. var lastTime = 0;
  469. var vendors = ['ms', 'moz', 'webkit', 'o'];
  470. for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  471. window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
  472. window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
  473. }
  474. if (!window.requestAnimationFrame) {
  475. window.requestAnimationFrame = function(callback, element) {
  476. var currTime = new Date().getTime();
  477. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  478. var id = window.setTimeout(function() { callback(currTime + timeToCall); },
  479. timeToCall);
  480. lastTime = currTime + timeToCall;
  481. return id;
  482. };
  483. }
  484. if (!window.cancelAnimationFrame) {
  485. window.cancelAnimationFrame = function(id) {
  486. clearTimeout(id);
  487. };
  488. }
  489. }());