lightbox.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /*!
  2. * Lightbox v2.11.4
  3. * by Lokesh Dhakar
  4. *
  5. * More info:
  6. * http://lokeshdhakar.com/projects/lightbox2/
  7. *
  8. * Copyright Lokesh Dhakar
  9. * Released under the MIT license
  10. * https://github.com/lokesh/lightbox2/blob/master/LICENSE
  11. *
  12. * @preserve
  13. */
  14. // Uses Node, AMD or browser globals to create a module.
  15. (function (root, factory) {
  16. if (typeof define === 'function' && define.amd) {
  17. // AMD. Register as an anonymous module.
  18. define(['jquery'], factory);
  19. } else if (typeof exports === 'object') {
  20. // Node. Does not work with strict CommonJS, but
  21. // only CommonJS-like environments that support module.exports,
  22. // like Node.
  23. module.exports = factory(require('jquery'));
  24. } else {
  25. // Browser globals (root is window)
  26. root.lightbox = factory(root.jQuery);
  27. }
  28. }(this, function ($) {
  29. function Lightbox(options) {
  30. this.album = [];
  31. this.currentImageIndex = void 0;
  32. this.init();
  33. // options
  34. this.options = $.extend({}, this.constructor.defaults);
  35. this.option(options);
  36. }
  37. // Descriptions of all options available on the demo site:
  38. // http://lokeshdhakar.com/projects/lightbox2/index.html#options
  39. Lightbox.defaults = {
  40. albumLabel: 'Image %1 of %2',
  41. alwaysShowNavOnTouchDevices: false,
  42. fadeDuration: 600,
  43. fitImagesInViewport: true,
  44. imageFadeDuration: 600,
  45. // maxWidth: 800,
  46. // maxHeight: 600,
  47. positionFromTop: 50,
  48. resizeDuration: 700,
  49. showImageNumberLabel: true,
  50. wrapAround: false,
  51. disableScrolling: false,
  52. /*
  53. Sanitize Title
  54. If the caption data is trusted, for example you are hardcoding it in, then leave this to false.
  55. This will free you to add html tags, such as links, in the caption.
  56. If the caption data is user submitted or from some other untrusted source, then set this to true
  57. to prevent xss and other injection attacks.
  58. */
  59. sanitizeTitle: false
  60. };
  61. Lightbox.prototype.option = function(options) {
  62. $.extend(this.options, options);
  63. };
  64. Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages) {
  65. return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
  66. };
  67. Lightbox.prototype.init = function() {
  68. var self = this;
  69. // Both enable and build methods require the body tag to be in the DOM.
  70. $(document).ready(function() {
  71. self.enable();
  72. self.build();
  73. });
  74. };
  75. // Loop through anchors and areamaps looking for either data-lightbox attributes or rel attributes
  76. // that contain 'lightbox'. When these are clicked, start lightbox.
  77. Lightbox.prototype.enable = function() {
  78. var self = this;
  79. $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(event) {
  80. self.start($(event.currentTarget));
  81. return false;
  82. });
  83. };
  84. // Build html for the lightbox and the overlay.
  85. // Attach event handlers to the new DOM elements. click click click
  86. Lightbox.prototype.build = function() {
  87. if ($('#lightbox').length > 0) {
  88. return;
  89. }
  90. var self = this;
  91. // The two root notes generated, #lightboxOverlay and #lightbox are given
  92. // tabindex attrs so they are focusable. We attach our keyboard event
  93. // listeners to these two elements, and not the document. Clicking anywhere
  94. // while Lightbox is opened will keep the focus on or inside one of these
  95. // two elements.
  96. //
  97. // We do this so we can prevent propogation of the Esc keypress when
  98. // Lightbox is open. This prevents it from intefering with other components
  99. // on the page below.
  100. //
  101. // Github issue: https://github.com/lokesh/lightbox2/issues/663
  102. $('<div id="lightboxOverlay" tabindex="-1" class="lightboxOverlay"></div><div id="lightbox" tabindex="-1" class="lightbox"><div class="lb-outerContainer"><div class="lb-container"><img class="lb-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt=""/><div class="lb-nav"><a class="lb-prev" role="button" tabindex="0" aria-label="Previous image" href="" ></a><a class="lb-next" role="button" tabindex="0" aria-label="Next image" href="" ></a></div><div class="lb-loader"><a class="lb-cancel" role="button" tabindex="0"></a></div></div></div><div class="lb-dataContainer"><div class="lb-data"><div class="lb-details"><span class="lb-caption"></span><span class="lb-number"></span></div><div class="lb-closeContainer"><a class="lb-close" role="button" tabindex="0"></a></div></div></div></div>').appendTo($('body'));
  103. // Cache jQuery objects
  104. this.$lightbox = $('#lightbox');
  105. this.$overlay = $('#lightboxOverlay');
  106. this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
  107. this.$container = this.$lightbox.find('.lb-container');
  108. this.$image = this.$lightbox.find('.lb-image');
  109. this.$nav = this.$lightbox.find('.lb-nav');
  110. // Store css values for future lookup
  111. this.containerPadding = {
  112. top: parseInt(this.$container.css('padding-top'), 10),
  113. right: parseInt(this.$container.css('padding-right'), 10),
  114. bottom: parseInt(this.$container.css('padding-bottom'), 10),
  115. left: parseInt(this.$container.css('padding-left'), 10)
  116. };
  117. this.imageBorderWidth = {
  118. top: parseInt(this.$image.css('border-top-width'), 10),
  119. right: parseInt(this.$image.css('border-right-width'), 10),
  120. bottom: parseInt(this.$image.css('border-bottom-width'), 10),
  121. left: parseInt(this.$image.css('border-left-width'), 10)
  122. };
  123. // Attach event handlers to the newly minted DOM elements
  124. this.$overlay.hide().on('click', function() {
  125. self.end();
  126. return false;
  127. });
  128. this.$lightbox.hide().on('click', function(event) {
  129. if ($(event.target).attr('id') === 'lightbox') {
  130. self.end();
  131. }
  132. });
  133. this.$outerContainer.on('click', function(event) {
  134. if ($(event.target).attr('id') === 'lightbox') {
  135. self.end();
  136. }
  137. return false;
  138. });
  139. this.$lightbox.find('.lb-prev').on('click', function() {
  140. if (self.currentImageIndex === 0) {
  141. self.changeImage(self.album.length - 1);
  142. } else {
  143. self.changeImage(self.currentImageIndex - 1);
  144. }
  145. return false;
  146. });
  147. this.$lightbox.find('.lb-next').on('click', function() {
  148. if (self.currentImageIndex === self.album.length - 1) {
  149. self.changeImage(0);
  150. } else {
  151. self.changeImage(self.currentImageIndex + 1);
  152. }
  153. return false;
  154. });
  155. /*
  156. Show context menu for image on right-click
  157. There is a div containing the navigation that spans the entire image and lives above of it. If
  158. you right-click, you are right clicking this div and not the image. This prevents users from
  159. saving the image or using other context menu actions with the image.
  160. To fix this, when we detect the right mouse button is pressed down, but not yet clicked, we
  161. set pointer-events to none on the nav div. This is so that the upcoming right-click event on
  162. the next mouseup will bubble down to the image. Once the right-click/contextmenu event occurs
  163. we set the pointer events back to auto for the nav div so it can capture hover and left-click
  164. events as usual.
  165. */
  166. this.$nav.on('mousedown', function(event) {
  167. if (event.which === 3) {
  168. self.$nav.css('pointer-events', 'none');
  169. self.$lightbox.one('contextmenu', function() {
  170. setTimeout(function() {
  171. this.$nav.css('pointer-events', 'auto');
  172. }.bind(self), 0);
  173. });
  174. }
  175. });
  176. this.$lightbox.find('.lb-loader, .lb-close').on('click keyup', function(e) {
  177. // If mouse click OR 'enter' or 'space' keypress, close LB
  178. if (
  179. e.type === 'click' || (e.type === 'keyup' && (e.which === 13 || e.which === 32))) {
  180. self.end();
  181. return false;
  182. }
  183. });
  184. };
  185. // Show overlay and lightbox. If the image is part of a set, add siblings to album array.
  186. Lightbox.prototype.start = function($link) {
  187. var self = this;
  188. var $window = $(window);
  189. $window.on('resize', $.proxy(this.sizeOverlay, this));
  190. this.sizeOverlay();
  191. this.album = [];
  192. var imageNumber = 0;
  193. function addToAlbum($link) {
  194. self.album.push({
  195. alt: $link.attr('data-alt'),
  196. link: $link.attr('href'),
  197. title: $link.attr('data-title') || $link.attr('title')
  198. });
  199. }
  200. // Support both data-lightbox attribute and rel attribute implementations
  201. var dataLightboxValue = $link.attr('data-lightbox');
  202. var $links;
  203. if (dataLightboxValue) {
  204. $links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
  205. for (var i = 0; i < $links.length; i = ++i) {
  206. addToAlbum($($links[i]));
  207. if ($links[i] === $link[0]) {
  208. imageNumber = i;
  209. }
  210. }
  211. } else {
  212. if ($link.attr('rel') === 'lightbox') {
  213. // If image is not part of a set
  214. addToAlbum($link);
  215. } else {
  216. // If image is part of a set
  217. $links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
  218. for (var j = 0; j < $links.length; j = ++j) {
  219. addToAlbum($($links[j]));
  220. if ($links[j] === $link[0]) {
  221. imageNumber = j;
  222. }
  223. }
  224. }
  225. }
  226. // Position Lightbox
  227. var top = $window.scrollTop() + this.options.positionFromTop;
  228. var left = $window.scrollLeft();
  229. this.$lightbox.css({
  230. top: top + 'px',
  231. left: left + 'px'
  232. }).fadeIn(this.options.fadeDuration);
  233. // Disable scrolling of the page while open
  234. if (this.options.disableScrolling) {
  235. $('body').addClass('lb-disable-scrolling');
  236. }
  237. this.changeImage(imageNumber);
  238. };
  239. // Hide most UI elements in preparation for the animated resizing of the lightbox.
  240. Lightbox.prototype.changeImage = function(imageNumber) {
  241. var self = this;
  242. var filename = this.album[imageNumber].link;
  243. var filetype = filename.split('.').slice(-1)[0];
  244. var $image = this.$lightbox.find('.lb-image');
  245. // Disable keyboard nav during transitions
  246. this.disableKeyboardNav();
  247. // Show loading state
  248. this.$overlay.fadeIn(this.options.fadeDuration);
  249. $('.lb-loader').fadeIn('slow');
  250. this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
  251. this.$outerContainer.addClass('animating');
  252. // When image to show is preloaded, we send the width and height to sizeContainer()
  253. var preloader = new Image();
  254. preloader.onload = function() {
  255. var $preloader;
  256. var imageHeight;
  257. var imageWidth;
  258. var maxImageHeight;
  259. var maxImageWidth;
  260. var windowHeight;
  261. var windowWidth;
  262. $image.attr({
  263. 'alt': self.album[imageNumber].alt,
  264. 'src': filename
  265. });
  266. $preloader = $(preloader);
  267. $image.width(preloader.width);
  268. $image.height(preloader.height);
  269. var aspectRatio = preloader.width / preloader.height;
  270. windowWidth = $(window).width();
  271. windowHeight = $(window).height();
  272. // Calculate the max image dimensions for the current viewport.
  273. // Take into account the border around the image and an additional 10px gutter on each side.
  274. maxImageWidth = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20;
  275. maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - self.options.positionFromTop - 70;
  276. /*
  277. Since many SVGs have small intrinsic dimensions, but they support scaling
  278. up without quality loss because of their vector format, max out their
  279. size inside the viewport.
  280. */
  281. if (filetype === 'svg') {
  282. if (aspectRatio >= 1) {
  283. imageWidth = maxImageWidth;
  284. imageHeight = parseInt(maxImageWidth / aspectRatio, 10);
  285. } else {
  286. imageWidth = parseInt(maxImageHeight / aspectRatio, 10);
  287. imageHeight = maxImageHeight;
  288. }
  289. $image.width(imageWidth);
  290. $image.height(imageHeight);
  291. } else {
  292. // Fit image inside the viewport.
  293. if (self.options.fitImagesInViewport) {
  294. // Check if image size is larger then maxWidth|maxHeight in settings
  295. if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
  296. maxImageWidth = self.options.maxWidth;
  297. }
  298. if (self.options.maxHeight && self.options.maxHeight < maxImageHeight) {
  299. maxImageHeight = self.options.maxHeight;
  300. }
  301. } else {
  302. maxImageWidth = self.options.maxWidth || preloader.width || maxImageWidth;
  303. maxImageHeight = self.options.maxHeight || preloader.height || maxImageHeight;
  304. }
  305. // Is the current image's width or height is greater than the maxImageWidth or maxImageHeight
  306. // option than we need to size down while maintaining the aspect ratio.
  307. if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
  308. if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
  309. imageWidth = maxImageWidth;
  310. imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
  311. $image.width(imageWidth);
  312. $image.height(imageHeight);
  313. } else {
  314. imageHeight = maxImageHeight;
  315. imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
  316. $image.width(imageWidth);
  317. $image.height(imageHeight);
  318. }
  319. }
  320. }
  321. self.sizeContainer($image.width(), $image.height());
  322. };
  323. // Preload image before showing
  324. preloader.src = this.album[imageNumber].link;
  325. this.currentImageIndex = imageNumber;
  326. };
  327. // Stretch overlay to fit the viewport
  328. Lightbox.prototype.sizeOverlay = function() {
  329. var self = this;
  330. /*
  331. We use a setTimeout 0 to pause JS execution and let the rendering catch-up.
  332. Why do this? If the `disableScrolling` option is set to true, a class is added to the body
  333. tag that disables scrolling and hides the scrollbar. We want to make sure the scrollbar is
  334. hidden before we measure the document width, as the presence of the scrollbar will affect the
  335. number.
  336. */
  337. setTimeout(function() {
  338. self.$overlay
  339. .width($(document).width())
  340. .height($(document).height());
  341. }, 0);
  342. };
  343. // Animate the size of the lightbox to fit the image we are showing
  344. // This method also shows the the image.
  345. Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
  346. var self = this;
  347. var oldWidth = this.$outerContainer.outerWidth();
  348. var oldHeight = this.$outerContainer.outerHeight();
  349. var newWidth = imageWidth + this.containerPadding.left + this.containerPadding.right + this.imageBorderWidth.left + this.imageBorderWidth.right;
  350. var newHeight = imageHeight + this.containerPadding.top + this.containerPadding.bottom + this.imageBorderWidth.top + this.imageBorderWidth.bottom;
  351. function postResize() {
  352. self.$lightbox.find('.lb-dataContainer').width(newWidth);
  353. self.$lightbox.find('.lb-prevLink').height(newHeight);
  354. self.$lightbox.find('.lb-nextLink').height(newHeight);
  355. // Set focus on one of the two root nodes so keyboard events are captured.
  356. self.$overlay.trigger('focus');
  357. self.showImage();
  358. }
  359. if (oldWidth !== newWidth || oldHeight !== newHeight) {
  360. this.$outerContainer.animate({
  361. width: newWidth,
  362. height: newHeight
  363. }, this.options.resizeDuration, 'swing', function() {
  364. postResize();
  365. });
  366. } else {
  367. postResize();
  368. }
  369. };
  370. // Display the image and its details and begin preload neighboring images.
  371. Lightbox.prototype.showImage = function() {
  372. this.$lightbox.find('.lb-loader').stop(true).hide();
  373. this.$lightbox.find('.lb-image').fadeIn(this.options.imageFadeDuration);
  374. this.updateNav();
  375. this.updateDetails();
  376. this.preloadNeighboringImages();
  377. this.enableKeyboardNav();
  378. };
  379. // Display previous and next navigation if appropriate.
  380. Lightbox.prototype.updateNav = function() {
  381. // Check to see if the browser supports touch events. If so, we take the conservative approach
  382. // and assume that mouse hover events are not supported and always show prev/next navigation
  383. // arrows in image sets.
  384. var alwaysShowNav = false;
  385. try {
  386. document.createEvent('TouchEvent');
  387. alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
  388. } catch (e) {}
  389. this.$lightbox.find('.lb-nav').show();
  390. if (this.album.length > 1) {
  391. if (this.options.wrapAround) {
  392. if (alwaysShowNav) {
  393. this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
  394. }
  395. this.$lightbox.find('.lb-prev, .lb-next').show();
  396. } else {
  397. if (this.currentImageIndex > 0) {
  398. this.$lightbox.find('.lb-prev').show();
  399. if (alwaysShowNav) {
  400. this.$lightbox.find('.lb-prev').css('opacity', '1');
  401. }
  402. }
  403. if (this.currentImageIndex < this.album.length - 1) {
  404. this.$lightbox.find('.lb-next').show();
  405. if (alwaysShowNav) {
  406. this.$lightbox.find('.lb-next').css('opacity', '1');
  407. }
  408. }
  409. }
  410. }
  411. };
  412. // Display caption, image number, and closing button.
  413. Lightbox.prototype.updateDetails = function() {
  414. var self = this;
  415. // Enable anchor clicks in the injected caption html.
  416. // Thanks Nate Wright for the fix. @https://github.com/NateWr
  417. if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
  418. this.album[this.currentImageIndex].title !== '') {
  419. var $caption = this.$lightbox.find('.lb-caption');
  420. if (this.options.sanitizeTitle) {
  421. $caption.text(this.album[this.currentImageIndex].title);
  422. } else {
  423. $caption.html(this.album[this.currentImageIndex].title);
  424. }
  425. $caption.fadeIn('fast');
  426. }
  427. if (this.album.length > 1 && this.options.showImageNumberLabel) {
  428. var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
  429. this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
  430. } else {
  431. this.$lightbox.find('.lb-number').hide();
  432. }
  433. this.$outerContainer.removeClass('animating');
  434. this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function() {
  435. return self.sizeOverlay();
  436. });
  437. };
  438. // Preload previous and next images in set.
  439. Lightbox.prototype.preloadNeighboringImages = function() {
  440. if (this.album.length > this.currentImageIndex + 1) {
  441. var preloadNext = new Image();
  442. preloadNext.src = this.album[this.currentImageIndex + 1].link;
  443. }
  444. if (this.currentImageIndex > 0) {
  445. var preloadPrev = new Image();
  446. preloadPrev.src = this.album[this.currentImageIndex - 1].link;
  447. }
  448. };
  449. Lightbox.prototype.enableKeyboardNav = function() {
  450. this.$lightbox.on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  451. this.$overlay.on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  452. };
  453. Lightbox.prototype.disableKeyboardNav = function() {
  454. this.$lightbox.off('.keyboard');
  455. this.$overlay.off('.keyboard');
  456. };
  457. Lightbox.prototype.keyboardAction = function(event) {
  458. var KEYCODE_ESC = 27;
  459. var KEYCODE_LEFTARROW = 37;
  460. var KEYCODE_RIGHTARROW = 39;
  461. var keycode = event.keyCode;
  462. if (keycode === KEYCODE_ESC) {
  463. // Prevent bubbling so as to not affect other components on the page.
  464. event.stopPropagation();
  465. this.end();
  466. } else if (keycode === KEYCODE_LEFTARROW) {
  467. if (this.currentImageIndex !== 0) {
  468. this.changeImage(this.currentImageIndex - 1);
  469. } else if (this.options.wrapAround && this.album.length > 1) {
  470. this.changeImage(this.album.length - 1);
  471. }
  472. } else if (keycode === KEYCODE_RIGHTARROW) {
  473. if (this.currentImageIndex !== this.album.length - 1) {
  474. this.changeImage(this.currentImageIndex + 1);
  475. } else if (this.options.wrapAround && this.album.length > 1) {
  476. this.changeImage(0);
  477. }
  478. }
  479. };
  480. // Closing time. :-(
  481. Lightbox.prototype.end = function() {
  482. this.disableKeyboardNav();
  483. $(window).off('resize', this.sizeOverlay);
  484. this.$lightbox.fadeOut(this.options.fadeDuration);
  485. this.$overlay.fadeOut(this.options.fadeDuration);
  486. if (this.options.disableScrolling) {
  487. $('body').removeClass('lb-disable-scrolling');
  488. }
  489. };
  490. return new Lightbox();
  491. }));