vegas.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*!-----------------------------------------------------------------------------
  2. * Vegas - Fullscreen Backgrounds and Slideshows.
  3. * v2.0.0-wip - built 2015-02-20
  4. * Licensed under the MIT License.
  5. * http://vegas.jaysalvat.com/
  6. * ----------------------------------------------------------------------------
  7. * Copyright (C) 2010-2015 Jay Salvat
  8. * http://jaysalvat.com/
  9. * --------------------------------------------------------------------------*/
  10. /* global jQuery, Zepto */
  11. (function ($) {
  12. 'use strict';
  13. var defaults = {
  14. slide: 0,
  15. delay: 5000,
  16. preload: false,
  17. preloadImage: false,
  18. preloadVideo: false,
  19. timer: true,
  20. overlay: false,
  21. autoplay: true,
  22. shuffle: false,
  23. cover: true,
  24. color: null,
  25. align: 'center',
  26. valign: 'center',
  27. transition: 'fade',
  28. transitionDuration: 1000,
  29. animation: null,
  30. animationDuration: 'auto',
  31. init: function () {},
  32. play: function () {},
  33. pause: function () {},
  34. walk: function () {},
  35. slides: [
  36. // {
  37. // src: null,
  38. // color: null,
  39. // delay: null,
  40. // align: null,
  41. // valign: null,
  42. // transition: null,
  43. // transitionDuration: null,
  44. // animation: null,
  45. // animationDuration: null,
  46. // cover: true,
  47. // videos: []
  48. // }
  49. // ...
  50. ]
  51. };
  52. var videoCache = {};
  53. var Vegas = function (elmt, options) {
  54. this.elmt = elmt;
  55. this.settings = $.extend({}, defaults, $.vegas.defaults, options);
  56. this.slide = this.settings.slide;
  57. this.total = this.settings.slides.length;
  58. this.noshow = this.total < 2;
  59. this.paused = !this.settings.autoplay || this.noshow;
  60. this.$elmt = $(elmt);
  61. this.$timer = null;
  62. this.$overlay = null;
  63. this.$slide = null;
  64. this.timeout = null;
  65. this.transitions = [];
  66. this.animations = [];
  67. this.support = {
  68. objectFit: 'objectFit' in document.body.style,
  69. transition: 'transition' in document.body.style || 'WebkitTransition' in document.body.style,
  70. video: $.vegas.isVideoCompatible()
  71. };
  72. for (var i = 0; i < document.styleSheets.length; i++) {
  73. var sheet = document.styleSheets[i],
  74. rules;
  75. try {
  76. rules = (sheet.cssRules || sheet.rules);
  77. } catch(e) {
  78. continue;
  79. }
  80. if (/vegas(\..*?)?(\.min)?\.css$/.test(sheet.href)) {
  81. for (var j = 0; j < rules.length; j++) {
  82. var rule = rules[j],
  83. matchTransition = /vegas\-transition\-([a-z0-9]*)/gi.exec(rule.selectorText),
  84. matchAnimation = /vegas\-animation\-([a-z0-9]*)/gi.exec(rule.selectorText);
  85. if (matchTransition && matchTransition[1]) {
  86. if (this.transitions.indexOf(matchTransition[1]) === -1) {
  87. this.transitions.push(matchTransition[1]);
  88. }
  89. }
  90. if (matchAnimation && matchAnimation[1]) {
  91. if (this.animations.indexOf(matchAnimation[1]) === -1) {
  92. this.animations.push(matchAnimation[1]);
  93. }
  94. }
  95. }
  96. }
  97. }
  98. if (this.settings.shuffle === true) {
  99. this.shuffle();
  100. }
  101. this._init();
  102. };
  103. Vegas.prototype = {
  104. _init: function () {
  105. var $wrapper,
  106. $overlay,
  107. $timer,
  108. isBody = this.elmt.tagName === 'BODY',
  109. timer = this.settings.timer,
  110. overlay = this.settings.overlay;
  111. // Preloading
  112. this._preload();
  113. // Wrapper with content
  114. if (!isBody) {
  115. this.$elmt.css('height', this.$elmt.css('height'));
  116. $wrapper = $('<div class="vegas-wrapper">')
  117. .css('overflow', this.$elmt.css('overflow'))
  118. .css('padding', this.$elmt.css('padding'));
  119. // Some browsers don't compute padding shorthand
  120. if (!this.$elmt.css('padding')) {
  121. $wrapper
  122. .css('padding-top', this.$elmt.css('padding-top'))
  123. .css('padding-bottom', this.$elmt.css('padding-bottom'))
  124. .css('padding-left', this.$elmt.css('padding-left'))
  125. .css('padding-right', this.$elmt.css('padding-right'));
  126. }
  127. this.$elmt.clone(true).children().appendTo($wrapper);
  128. this.elmt.innerHTML = '';
  129. }
  130. // Timer
  131. if (timer && this.support.transition) {
  132. $timer = $('<div class="vegas-timer"><div class="vegas-timer-progress">');
  133. this.$timer = $timer;
  134. this.$elmt.prepend($timer);
  135. }
  136. // Overlay
  137. if (overlay) {
  138. $overlay = $('<div class="vegas-overlay">');
  139. if (typeof overlay === 'string') {
  140. $overlay.css('background-image', 'url(' + overlay + ')');
  141. }
  142. this.$overlay = $overlay;
  143. this.$elmt.prepend($overlay);
  144. }
  145. // Container
  146. this.$elmt.addClass('vegas-container');
  147. if (!isBody) {
  148. this.$elmt.append($wrapper);
  149. }
  150. this.trigger('init');
  151. this._goto(this.slide);
  152. },
  153. _preload: function () {
  154. var video, img, i;
  155. for (i = 0; i < this.settings.slides.length; i++) {
  156. if (this.settings.preload || this.settings.preloadImages) {
  157. if (this.settings.slides[i].src) {
  158. img = new Image();
  159. img.src = this.settings.slides[i].src;
  160. }
  161. }
  162. if (this.settings.preload || this.settings.preloadVideos) {
  163. if (this.support.video && this.settings.slides[i].video) {
  164. video = this._video(this.settings.slides[i].video);
  165. video.preload = true;
  166. video.muted = true;
  167. videoCache[this.settings.slides[i].video.toString()] = video;
  168. }
  169. }
  170. }
  171. },
  172. _random: function (array) {
  173. return array[Math.floor(Math.random() * (array.length - 1))];
  174. },
  175. _slideShow: function () {
  176. var self = this;
  177. if (this.total > 1 && !this.paused && !this.noshow) {
  178. this.timeout = setTimeout(function () {
  179. self.next();
  180. }, this._options('delay'));
  181. }
  182. },
  183. _timer: function (state) {
  184. var self = this;
  185. clearTimeout(this.timeout);
  186. if (!this.$timer) {
  187. return;
  188. }
  189. this.$timer
  190. .removeClass('vegas-timer-running')
  191. .find('div')
  192. .css('transition-duration', '0ms');
  193. if (this.paused || this.noshow) {
  194. return;
  195. }
  196. if (state) {
  197. setTimeout(function () {
  198. self.$timer
  199. .addClass('vegas-timer-running')
  200. .find('div')
  201. .css('transition-duration', self._options('delay') - 100 + 'ms');
  202. }, 100);
  203. }
  204. },
  205. _video: function (srcs) {
  206. var video,
  207. source;
  208. if (videoCache[srcs.toString()]) {
  209. return videoCache[srcs.toString()];
  210. }
  211. if (srcs instanceof Array === false) {
  212. srcs = [ srcs ];
  213. }
  214. video = document.createElement('video');
  215. srcs.forEach(function (src) {
  216. source = document.createElement('source');
  217. source.src = src;
  218. video.appendChild(source);
  219. });
  220. return video;
  221. },
  222. _options: function (key, i) {
  223. if (i === undefined) {
  224. i = this.slide;
  225. }
  226. if (this.settings.slides[i][key] !== undefined) {
  227. return this.settings.slides[i][key];
  228. }
  229. return this.settings[key];
  230. },
  231. _goto: function (nb) {
  232. if (typeof this.settings.slides[nb] === 'undefined') {
  233. nb = 0;
  234. }
  235. this.slide = nb;
  236. var $slide,
  237. $inner,
  238. self = this,
  239. $slides = this.$elmt.children('.vegas-slide'),
  240. src = this.settings.slides[nb].src,
  241. videos = this.settings.slides[nb].video,
  242. delay = this._options('delay'),
  243. align = this._options('align'),
  244. valign = this._options('valign'),
  245. color = this._options('color') || this.$elmt.css('background-color'),
  246. cover = this._options('cover') ? 'cover' : 'contain',
  247. total = $slides.length,
  248. video,
  249. img;
  250. var transition = this._options('transition'),
  251. transitionDuration = this._options('transitionDuration'),
  252. animation = this._options('animation' ),
  253. animationDuration = this._options('animationDuration');
  254. if (transition === 'random' || transition instanceof Array) {
  255. if (transition instanceof Array) {
  256. transition = this._random(transition);
  257. } else {
  258. transition = this._random(this.transitions);
  259. }
  260. }
  261. if (transition && transition !== 'none' && this.transitions.indexOf(transition) < 0) {
  262. console.error("Vegas: Transition " + transition + " doesn't exist.");
  263. }
  264. if (transitionDuration === 'auto' || transitionDuration > delay) {
  265. transitionDuration = delay;
  266. }
  267. if (animation === 'random' || animation instanceof Array) {
  268. if (animation instanceof Array) {
  269. animation = this._random(animation);
  270. } else {
  271. animation = this._random(this.animations);
  272. }
  273. }
  274. if (animation && animation !== 'none' && this.animations.indexOf(animation) < 0) {
  275. console.error("Vegas: Animation " + animation + " doesn't exist.");
  276. }
  277. if (animationDuration === 'auto') {
  278. animationDuration = delay;
  279. }
  280. // Video ?
  281. if (this.support.video && videos) {
  282. video = this._video(videos);
  283. $slide = $(video)
  284. .addClass('vegas-video')
  285. .addClass('vegas-slide')
  286. .addClass('vegas-transition-' + transition)
  287. .css('background-color', color);
  288. if (this.support.objectFit) {
  289. $slide
  290. .css('object-position', align + ' ' + valign)
  291. .css('object-fit', cover)
  292. .css('width', '100%')
  293. .css('height', '100%');
  294. } else if (cover === 'contain') {
  295. $slide
  296. .css('width', '100%')
  297. .css('height', '100%');
  298. }
  299. // Image ?
  300. } else {
  301. img = new Image();
  302. $slide = $('<div></div>')
  303. .addClass('vegas-slide')
  304. .addClass('vegas-transition-' + transition);
  305. $inner = $('<div></div>')
  306. .addClass('vegas-slide-inner')
  307. .css('background-image', 'url(' + src + ')')
  308. .css('background-color', color)
  309. .css('background-position', align + ' ' + valign)
  310. .css('background-size', cover);
  311. if (animation) {
  312. $inner
  313. .addClass('vegas-animation-' + animation)
  314. .css('animation-duration', animationDuration + 'ms');
  315. }
  316. $slide.append($inner);
  317. }
  318. if (!self.support.transition) {
  319. $slide.css('display', 'none');
  320. }
  321. if (total) {
  322. $slides.eq(total - 1).after($slide);
  323. } else {
  324. this.$elmt.prepend($slide);
  325. }
  326. $slides
  327. .css('transition', 'all 0ms')
  328. .each(function () {
  329. this.className = ' vegas-slide';
  330. this.className += ' vegas-transition-' + transition;
  331. this.className += ' vegas-transition-' + transition + '-in';
  332. if (this.tagName === 'VIDEO') {
  333. this.className += ' vegas-video';
  334. }
  335. }
  336. );
  337. self._timer(false);
  338. function go () {
  339. self._timer(true);
  340. setTimeout(function () {
  341. if (self.support.transition) {
  342. $slides
  343. .css('transition', 'all ' + transitionDuration + 'ms')
  344. .addClass('vegas-transition-' + transition + '-out');
  345. }
  346. $slide
  347. .css('transition', 'all ' + transitionDuration + 'ms')
  348. .addClass('vegas-transition-' + transition + '-in');
  349. if (!self.support.transition) {
  350. $slide.fadeIn(transitionDuration);
  351. }
  352. for (var i = 0; i < $slides.length - 1; i++) {
  353. $slides.eq(i).remove();
  354. }
  355. self.trigger('walk');
  356. self._slideShow();
  357. }, 100);
  358. }
  359. if (video) {
  360. if (video.readyState === 4) {
  361. video.currentTime = 0;
  362. video.play();
  363. go();
  364. } else {
  365. video.oncanplay = function () {
  366. video.play();
  367. if (!video._started) {
  368. video._started = true;
  369. go();
  370. }
  371. };
  372. }
  373. } else {
  374. img.src = src;
  375. img.onload = go;
  376. }
  377. },
  378. shuffle: function () {
  379. var temp,
  380. rand;
  381. for (var i = this.total - 1; i > 0; i--) {
  382. rand = Math.floor(Math.random() * (i + 1));
  383. temp = this.settings.slides[i];
  384. this.settings.slides[i] = this.settings.slides[rand];
  385. this.settings.slides[rand] = temp;
  386. }
  387. },
  388. play: function () {
  389. if (this.paused) {
  390. this.paused = false;
  391. this.next();
  392. this.trigger('play');
  393. }
  394. },
  395. pause: function () {
  396. this._timer(false);
  397. this.paused = true;
  398. this.trigger('pause');
  399. },
  400. toggle: function () {
  401. if (this.paused) {
  402. this.play();
  403. } else {
  404. this.pause();
  405. }
  406. },
  407. playing: function () {
  408. return !this.paused && !this.noshow;
  409. },
  410. current: function (advanced) {
  411. if (advanced) {
  412. return {
  413. slide: this.slide,
  414. data: this.settings.slides[this.slide]
  415. };
  416. }
  417. return this.slide;
  418. },
  419. jump: function (nb) {
  420. if (nb < 0 || nb > this.total - 1 || nb === this.slide) {
  421. return;
  422. }
  423. this.slide = nb;
  424. this._goto(this.slide);
  425. },
  426. next: function () {
  427. this.slide++;
  428. if (this.slide >= this.total) {
  429. this.slide = 0;
  430. }
  431. this._goto(this.slide);
  432. },
  433. previous: function () {
  434. this.slide--;
  435. if (this.slide < 0) {
  436. this.slide = this.total - 1;
  437. }
  438. this._goto(this.slide);
  439. },
  440. trigger: function (fn) {
  441. var params = [];
  442. if (fn !== 'init') {
  443. params = [
  444. this.slide,
  445. this.settings.slides[this.slide]
  446. ];
  447. }
  448. this.$elmt.trigger('vegas' + fn, params);
  449. if (typeof this.settings[fn] === 'function') {
  450. this.settings[fn].apply(this.$elmt, params);
  451. }
  452. },
  453. options: function (key, value) {
  454. var oldSlides = this.settings.slides;
  455. if (typeof key === 'object') {
  456. this.settings = $.extend({}, defaults, $.vegas.defaults, key);
  457. } else if (typeof key === 'string') {
  458. if (value === undefined) {
  459. return this.settings[key];
  460. }
  461. this.settings[key] = value;
  462. } else {
  463. return this.settings;
  464. }
  465. // In case slides have changed
  466. if (this.settings.slides !== oldSlides) {
  467. this.total = this.settings.slides.length;
  468. this.noshow = this.total < 2;
  469. this._preload();
  470. }
  471. }
  472. };
  473. $.fn.vegas = function(options) {
  474. var args = arguments,
  475. error = false,
  476. returns;
  477. if (options === undefined || typeof options === 'object') {
  478. return this.each(function () {
  479. if (!this._vegas) {
  480. this._vegas = new Vegas(this, options);
  481. }
  482. });
  483. } else if (typeof options === 'string') {
  484. this.each(function () {
  485. var instance = this._vegas;
  486. if (!instance) {
  487. throw new Error('No Vegas applied to this element.');
  488. }
  489. if (typeof instance[options] === 'function' && options[0] !== '_') {
  490. returns = instance[options].apply(instance, [].slice.call(args, 1));
  491. } else {
  492. error = true;
  493. }
  494. });
  495. if (error) {
  496. throw new Error('No method "' + options + '" in Vegas.');
  497. }
  498. return returns !== undefined ? returns : this;
  499. }
  500. };
  501. $.vegas = {};
  502. $.vegas.defaults = defaults;
  503. $.vegas.isVideoCompatible = function () {
  504. return !/(Android|webOS|Phone|iPad|iPod|BlackBerry|Windows Phone)/i.test(navigator.userAgent);
  505. };
  506. })(typeof jQuery !== 'undefined' ? jQuery :
  507. typeof Zepto !== 'undefined' ? Zepto : null
  508. );