vegas.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. }
  166. }
  167. }
  168. },
  169. _random: function (array) {
  170. return array[Math.floor(Math.random() * (array.length - 1))];
  171. },
  172. _slideShow: function () {
  173. var self = this;
  174. if (this.total > 1 && !this.paused && !this.noshow) {
  175. this.timeout = setTimeout(function () {
  176. self.next();
  177. }, this._options('delay'));
  178. }
  179. },
  180. _timer: function (state) {
  181. var self = this;
  182. clearTimeout(this.timeout);
  183. if (!this.$timer) {
  184. return;
  185. }
  186. this.$timer
  187. .removeClass('vegas-timer-running')
  188. .find('div')
  189. .css('transition-duration', '0ms');
  190. if (this.paused || this.noshow) {
  191. return;
  192. }
  193. if (state) {
  194. setTimeout(function () {
  195. self.$timer
  196. .addClass('vegas-timer-running')
  197. .find('div')
  198. .css('transition-duration', self._options('delay') - 100 + 'ms');
  199. }, 100);
  200. }
  201. },
  202. _video: function (srcs) {
  203. var video,
  204. source,
  205. cacheKey = srcs.toString();
  206. if (videoCache[cacheKey]) {
  207. return videoCache[cacheKey];
  208. }
  209. if (srcs instanceof Array === false) {
  210. srcs = [ srcs ];
  211. }
  212. video = document.createElement('video');
  213. video.muted = true;
  214. video.preload = true;
  215. srcs.forEach(function (src) {
  216. source = document.createElement('source');
  217. source.src = src;
  218. video.appendChild(source);
  219. });
  220. videoCache[cacheKey] = video;
  221. return video;
  222. },
  223. _options: function (key, i) {
  224. if (i === undefined) {
  225. i = this.slide;
  226. }
  227. if (this.settings.slides[i][key] !== undefined) {
  228. return this.settings.slides[i][key];
  229. }
  230. return this.settings[key];
  231. },
  232. _goto: function (nb) {
  233. if (typeof this.settings.slides[nb] === 'undefined') {
  234. nb = 0;
  235. }
  236. this.slide = nb;
  237. var $slide,
  238. $inner,
  239. $video,
  240. $slides = this.$elmt.children('.vegas-slide'),
  241. src = this.settings.slides[nb].src,
  242. videos = this.settings.slides[nb].video,
  243. delay = this._options('delay'),
  244. align = this._options('align'),
  245. valign = this._options('valign'),
  246. color = this._options('color') || this.$elmt.css('background-color'),
  247. cover = this._options('cover') ? 'cover' : 'contain',
  248. self = this,
  249. total = $slides.length,
  250. video,
  251. img;
  252. var transition = this._options('transition'),
  253. transitionDuration = this._options('transitionDuration'),
  254. animation = this._options('animation' ),
  255. animationDuration = this._options('animationDuration');
  256. if (transition === 'random' || transition instanceof Array) {
  257. if (transition instanceof Array) {
  258. transition = this._random(transition);
  259. } else {
  260. transition = this._random(this.transitions);
  261. }
  262. }
  263. if (animation === 'random' || animation instanceof Array) {
  264. if (animation instanceof Array) {
  265. animation = this._random(animation);
  266. } else {
  267. animation = this._random(this.animations);
  268. }
  269. }
  270. if (transition && transition !== 'none' && this.transitions.indexOf(transition) < 0) {
  271. console.error("Vegas: Transition " + transition + " doesn't exist.");
  272. }
  273. if (animation && animation !== 'none' && this.animations.indexOf(animation) < 0) {
  274. console.error("Vegas: Animation " + animation + " doesn't exist.");
  275. }
  276. if (transitionDuration === 'auto' || transitionDuration > delay) {
  277. transitionDuration = delay;
  278. }
  279. if (animationDuration === 'auto') {
  280. animationDuration = delay;
  281. }
  282. $slide = $('<div class="vegas-slide"></div>');
  283. if (transition) {
  284. $slide.addClass('vegas-transition-' + transition);
  285. }
  286. // Video ?
  287. if (this.support.video && videos) {
  288. video = this._video(videos);
  289. $video = $(video)
  290. .addClass('vegas-video')
  291. .css('background-color', color);
  292. if (this.support.objectFit) {
  293. $video
  294. .css('object-position', align + ' ' + valign)
  295. .css('object-fit', cover)
  296. .css('width', '100%')
  297. .css('height', '100%');
  298. } else if (cover === 'contain') {
  299. $video
  300. .css('width', '100%')
  301. .css('height', '100%');
  302. }
  303. $slide.append($video);
  304. // Image ?
  305. } else {
  306. img = new Image();
  307. $inner = $('<div class="vegas-slide-inner"></div>')
  308. .css('background-image', 'url(' + src + ')')
  309. .css('background-color', color)
  310. .css('background-position', align + ' ' + valign)
  311. .css('background-size', cover);
  312. if (animation) {
  313. $inner
  314. .addClass('vegas-animation-' + animation)
  315. .css('animation-duration', animationDuration + 'ms');
  316. }
  317. $slide.append($inner);
  318. }
  319. if (!self.support.transition) {
  320. $slide.css('display', 'none');
  321. }
  322. if (total) {
  323. $slides.eq(total - 1).after($slide);
  324. } else {
  325. this.$elmt.prepend($slide);
  326. }
  327. $slides
  328. .css('transition', 'all 0ms')
  329. .each(function () {
  330. this.className = 'vegas-slide';
  331. if (this.tagName === 'VIDEO') {
  332. this.className += ' vegas-video';
  333. }
  334. if (transition) {
  335. this.className += ' vegas-transition-' + transition;
  336. this.className += ' vegas-transition-' + transition + '-in';
  337. }
  338. }
  339. );
  340. self._timer(false);
  341. function go () {
  342. self._timer(true);
  343. setTimeout(function () {
  344. if (transition) {
  345. if (self.support.transition) {
  346. $slides
  347. .css('transition', 'all ' + transitionDuration + 'ms')
  348. .addClass('vegas-transition-' + transition + '-out');
  349. $slide
  350. .css('transition', 'all ' + transitionDuration + 'ms')
  351. .addClass('vegas-transition-' + transition + '-in');
  352. } else {
  353. $slide.fadeIn(transitionDuration);
  354. }
  355. }
  356. for (var i = 0; i < $slides.length - 1; i++) {
  357. $slides.eq(i).remove();
  358. }
  359. self.trigger('walk');
  360. self._slideShow();
  361. }, 100);
  362. }
  363. if (video) {
  364. if (video.readyState === 4) {
  365. video.currentTime = 0;
  366. video.play();
  367. go();
  368. } else {
  369. video.oncanplay = function () {
  370. video.play();
  371. if (!video._started) {
  372. video._started = true;
  373. go();
  374. }
  375. };
  376. }
  377. } else {
  378. img.src = src;
  379. img.onload = go;
  380. }
  381. },
  382. shuffle: function () {
  383. var temp,
  384. rand;
  385. for (var i = this.total - 1; i > 0; i--) {
  386. rand = Math.floor(Math.random() * (i + 1));
  387. temp = this.settings.slides[i];
  388. this.settings.slides[i] = this.settings.slides[rand];
  389. this.settings.slides[rand] = temp;
  390. }
  391. },
  392. play: function () {
  393. if (this.paused) {
  394. this.paused = false;
  395. this.next();
  396. this.trigger('play');
  397. }
  398. },
  399. pause: function () {
  400. this._timer(false);
  401. this.paused = true;
  402. this.trigger('pause');
  403. },
  404. toggle: function () {
  405. if (this.paused) {
  406. this.play();
  407. } else {
  408. this.pause();
  409. }
  410. },
  411. playing: function () {
  412. return !this.paused && !this.noshow;
  413. },
  414. current: function (advanced) {
  415. if (advanced) {
  416. return {
  417. slide: this.slide,
  418. data: this.settings.slides[this.slide]
  419. };
  420. }
  421. return this.slide;
  422. },
  423. jump: function (nb) {
  424. if (nb < 0 || nb > this.total - 1 || nb === this.slide) {
  425. return;
  426. }
  427. this.slide = nb;
  428. this._goto(this.slide);
  429. },
  430. next: function () {
  431. this.slide++;
  432. if (this.slide >= this.total) {
  433. this.slide = 0;
  434. }
  435. this._goto(this.slide);
  436. },
  437. previous: function () {
  438. this.slide--;
  439. if (this.slide < 0) {
  440. this.slide = this.total - 1;
  441. }
  442. this._goto(this.slide);
  443. },
  444. trigger: function (fn) {
  445. var params = [];
  446. if (fn !== 'init') {
  447. params = [
  448. this.slide,
  449. this.settings.slides[this.slide]
  450. ];
  451. }
  452. this.$elmt.trigger('vegas' + fn, params);
  453. if (typeof this.settings[fn] === 'function') {
  454. this.settings[fn].apply(this.$elmt, params);
  455. }
  456. },
  457. options: function (key, value) {
  458. var oldSlides = this.settings.slides;
  459. if (typeof key === 'object') {
  460. this.settings = $.extend({}, defaults, $.vegas.defaults, key);
  461. } else if (typeof key === 'string') {
  462. if (value === undefined) {
  463. return this.settings[key];
  464. }
  465. this.settings[key] = value;
  466. } else {
  467. return this.settings;
  468. }
  469. // In case slides have changed
  470. if (this.settings.slides !== oldSlides) {
  471. this.total = this.settings.slides.length;
  472. this.noshow = this.total < 2;
  473. this._preload();
  474. }
  475. }
  476. };
  477. $.fn.vegas = function(options) {
  478. var args = arguments,
  479. error = false,
  480. returns;
  481. if (options === undefined || typeof options === 'object') {
  482. return this.each(function () {
  483. if (!this._vegas) {
  484. this._vegas = new Vegas(this, options);
  485. }
  486. });
  487. } else if (typeof options === 'string') {
  488. this.each(function () {
  489. var instance = this._vegas;
  490. if (!instance) {
  491. throw new Error('No Vegas applied to this element.');
  492. }
  493. if (typeof instance[options] === 'function' && options[0] !== '_') {
  494. returns = instance[options].apply(instance, [].slice.call(args, 1));
  495. } else {
  496. error = true;
  497. }
  498. });
  499. if (error) {
  500. throw new Error('No method "' + options + '" in Vegas.');
  501. }
  502. return returns !== undefined ? returns : this;
  503. }
  504. };
  505. $.vegas = {};
  506. $.vegas.defaults = defaults;
  507. $.vegas.isVideoCompatible = function () {
  508. return !/(Android|webOS|Phone|iPad|iPod|BlackBerry|Windows Phone)/i.test(navigator.userAgent);
  509. };
  510. })(typeof jQuery !== 'undefined' ? jQuery :
  511. typeof Zepto !== 'undefined' ? Zepto : null
  512. );