vegas.js 19 KB

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