lightbox.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /*!
  2. * Lightbox v2.11.2
  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" aria-label="Previous image" href="" ></a><a class="lb-next" aria-label="Next image" href="" ></a></div><div class="lb-loader"><a class="lb-cancel"></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"></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', function() {
  177. self.end();
  178. return false;
  179. });
  180. };
  181. // Show overlay and lightbox. If the image is part of a set, add siblings to album array.
  182. Lightbox.prototype.start = function($link) {
  183. var self = this;
  184. var $window = $(window);
  185. $window.on('resize', $.proxy(this.sizeOverlay, this));
  186. this.sizeOverlay();
  187. this.album = [];
  188. var imageNumber = 0;
  189. function addToAlbum($link) {
  190. self.album.push({
  191. alt: $link.attr('data-alt'),
  192. link: $link.attr('href'),
  193. title: $link.attr('data-title') || $link.attr('title')
  194. });
  195. }
  196. // Support both data-lightbox attribute and rel attribute implementations
  197. var dataLightboxValue = $link.attr('data-lightbox');
  198. var $links;
  199. if (dataLightboxValue) {
  200. $links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
  201. for (var i = 0; i < $links.length; i = ++i) {
  202. addToAlbum($($links[i]));
  203. if ($links[i] === $link[0]) {
  204. imageNumber = i;
  205. }
  206. }
  207. } else {
  208. if ($link.attr('rel') === 'lightbox') {
  209. // If image is not part of a set
  210. addToAlbum($link);
  211. } else {
  212. // If image is part of a set
  213. $links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
  214. for (var j = 0; j < $links.length; j = ++j) {
  215. addToAlbum($($links[j]));
  216. if ($links[j] === $link[0]) {
  217. imageNumber = j;
  218. }
  219. }
  220. }
  221. }
  222. // Position Lightbox
  223. var top = $window.scrollTop() + this.options.positionFromTop;
  224. var left = $window.scrollLeft();
  225. this.$lightbox.css({
  226. top: top + 'px',
  227. left: left + 'px'
  228. }).fadeIn(this.options.fadeDuration);
  229. // Disable scrolling of the page while open
  230. if (this.options.disableScrolling) {
  231. $('body').addClass('lb-disable-scrolling');
  232. }
  233. this.changeImage(imageNumber);
  234. };
  235. // Hide most UI elements in preparation for the animated resizing of the lightbox.
  236. Lightbox.prototype.changeImage = function(imageNumber) {
  237. var self = this;
  238. var filename = this.album[imageNumber].link;
  239. var filetype = filename.split('.').slice(-1)[0];
  240. var $image = this.$lightbox.find('.lb-image');
  241. // Disable keyboard nav during transitions
  242. this.disableKeyboardNav();
  243. // Show loading state
  244. this.$overlay.fadeIn(this.options.fadeDuration);
  245. $('.lb-loader').fadeIn('slow');
  246. this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
  247. this.$outerContainer.addClass('animating');
  248. // When image to show is preloaded, we send the width and height to sizeContainer()
  249. var preloader = new Image();
  250. preloader.onload = function() {
  251. var $preloader;
  252. var imageHeight;
  253. var imageWidth;
  254. var maxImageHeight;
  255. var maxImageWidth;
  256. var windowHeight;
  257. var windowWidth;
  258. $image.attr({
  259. 'alt': self.album[imageNumber].alt,
  260. 'src': filename
  261. });
  262. $preloader = $(preloader);
  263. $image.width(preloader.width);
  264. $image.height(preloader.height);
  265. windowWidth = $(window).width();
  266. windowHeight = $(window).height();
  267. // Calculate the max image dimensions for the current viewport.
  268. // Take into account the border around the image and an additional 10px gutter on each side.
  269. maxImageWidth = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20;
  270. maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - self.options.positionFromTop - 70;
  271. /*
  272. Since many SVGs have small intrinsic dimensions, but they support scaling
  273. up without quality loss because of their vector format, max out their
  274. size.
  275. */
  276. if (filetype === 'svg') {
  277. $image.width(maxImageWidth);
  278. $image.height(maxImageHeight);
  279. }
  280. // Fit image inside the viewport.
  281. if (self.options.fitImagesInViewport) {
  282. // Check if image size is larger then maxWidth|maxHeight in settings
  283. if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
  284. maxImageWidth = self.options.maxWidth;
  285. }
  286. if (self.options.maxHeight && self.options.maxHeight < maxImageHeight) {
  287. maxImageHeight = self.options.maxHeight;
  288. }
  289. } else {
  290. maxImageWidth = self.options.maxWidth || preloader.width || maxImageWidth;
  291. maxImageHeight = self.options.maxHeight || preloader.height || maxImageHeight;
  292. }
  293. // Is the current image's width or height is greater than the maxImageWidth or maxImageHeight
  294. // option than we need to size down while maintaining the aspect ratio.
  295. if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
  296. if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
  297. imageWidth = maxImageWidth;
  298. imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
  299. $image.width(imageWidth);
  300. $image.height(imageHeight);
  301. } else {
  302. imageHeight = maxImageHeight;
  303. imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
  304. $image.width(imageWidth);
  305. $image.height(imageHeight);
  306. }
  307. }
  308. self.sizeContainer($image.width(), $image.height());
  309. };
  310. // Preload image before showing
  311. preloader.src = this.album[imageNumber].link;
  312. this.currentImageIndex = imageNumber;
  313. };
  314. // Stretch overlay to fit the viewport
  315. Lightbox.prototype.sizeOverlay = function() {
  316. var self = this;
  317. /*
  318. We use a setTimeout 0 to pause JS execution and let the rendering catch-up.
  319. Why do this? If the `disableScrolling` option is set to true, a class is added to the body
  320. tag that disables scrolling and hides the scrollbar. We want to make sure the scrollbar is
  321. hidden before we measure the document width, as the presence of the scrollbar will affect the
  322. number.
  323. */
  324. setTimeout(function() {
  325. self.$overlay
  326. .width($(document).width())
  327. .height($(document).height());
  328. }, 0);
  329. };
  330. // Animate the size of the lightbox to fit the image we are showing
  331. // This method also shows the the image.
  332. Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
  333. var self = this;
  334. var oldWidth = this.$outerContainer.outerWidth();
  335. var oldHeight = this.$outerContainer.outerHeight();
  336. var newWidth = imageWidth + this.containerPadding.left + this.containerPadding.right + this.imageBorderWidth.left + this.imageBorderWidth.right;
  337. var newHeight = imageHeight + this.containerPadding.top + this.containerPadding.bottom + this.imageBorderWidth.top + this.imageBorderWidth.bottom;
  338. function postResize() {
  339. self.$lightbox.find('.lb-dataContainer').width(newWidth);
  340. self.$lightbox.find('.lb-prevLink').height(newHeight);
  341. self.$lightbox.find('.lb-nextLink').height(newHeight);
  342. // Set focus on one of the two root nodes so keyboard events are captured.
  343. self.$overlay.focus();
  344. self.showImage();
  345. }
  346. if (oldWidth !== newWidth || oldHeight !== newHeight) {
  347. this.$outerContainer.animate({
  348. width: newWidth,
  349. height: newHeight
  350. }, this.options.resizeDuration, 'swing', function() {
  351. postResize();
  352. });
  353. } else {
  354. postResize();
  355. }
  356. };
  357. // Display the image and its details and begin preload neighboring images.
  358. Lightbox.prototype.showImage = function() {
  359. this.$lightbox.find('.lb-loader').stop(true).hide();
  360. this.$lightbox.find('.lb-image').fadeIn(this.options.imageFadeDuration);
  361. this.updateNav();
  362. this.updateDetails();
  363. this.preloadNeighboringImages();
  364. this.enableKeyboardNav();
  365. };
  366. // Display previous and next navigation if appropriate.
  367. Lightbox.prototype.updateNav = function() {
  368. // Check to see if the browser supports touch events. If so, we take the conservative approach
  369. // and assume that mouse hover events are not supported and always show prev/next navigation
  370. // arrows in image sets.
  371. var alwaysShowNav = false;
  372. try {
  373. document.createEvent('TouchEvent');
  374. alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
  375. } catch (e) {}
  376. this.$lightbox.find('.lb-nav').show();
  377. if (this.album.length > 1) {
  378. if (this.options.wrapAround) {
  379. if (alwaysShowNav) {
  380. this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
  381. }
  382. this.$lightbox.find('.lb-prev, .lb-next').show();
  383. } else {
  384. if (this.currentImageIndex > 0) {
  385. this.$lightbox.find('.lb-prev').show();
  386. if (alwaysShowNav) {
  387. this.$lightbox.find('.lb-prev').css('opacity', '1');
  388. }
  389. }
  390. if (this.currentImageIndex < this.album.length - 1) {
  391. this.$lightbox.find('.lb-next').show();
  392. if (alwaysShowNav) {
  393. this.$lightbox.find('.lb-next').css('opacity', '1');
  394. }
  395. }
  396. }
  397. }
  398. };
  399. // Display caption, image number, and closing button.
  400. Lightbox.prototype.updateDetails = function() {
  401. var self = this;
  402. // Enable anchor clicks in the injected caption html.
  403. // Thanks Nate Wright for the fix. @https://github.com/NateWr
  404. if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
  405. this.album[this.currentImageIndex].title !== '') {
  406. var $caption = this.$lightbox.find('.lb-caption');
  407. if (this.options.sanitizeTitle) {
  408. $caption.text(this.album[this.currentImageIndex].title);
  409. } else {
  410. $caption.html(this.album[this.currentImageIndex].title);
  411. }
  412. $caption.fadeIn('fast');
  413. }
  414. if (this.album.length > 1 && this.options.showImageNumberLabel) {
  415. var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
  416. this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
  417. } else {
  418. this.$lightbox.find('.lb-number').hide();
  419. }
  420. this.$outerContainer.removeClass('animating');
  421. this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function() {
  422. return self.sizeOverlay();
  423. });
  424. };
  425. // Preload previous and next images in set.
  426. Lightbox.prototype.preloadNeighboringImages = function() {
  427. if (this.album.length > this.currentImageIndex + 1) {
  428. var preloadNext = new Image();
  429. preloadNext.src = this.album[this.currentImageIndex + 1].link;
  430. }
  431. if (this.currentImageIndex > 0) {
  432. var preloadPrev = new Image();
  433. preloadPrev.src = this.album[this.currentImageIndex - 1].link;
  434. }
  435. };
  436. Lightbox.prototype.enableKeyboardNav = function() {
  437. this.$lightbox.on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  438. this.$overlay.on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  439. };
  440. Lightbox.prototype.disableKeyboardNav = function() {
  441. this.$lightbox.off('.keyboard');
  442. this.$overlay.off('.keyboard');
  443. };
  444. Lightbox.prototype.keyboardAction = function(event) {
  445. var KEYCODE_ESC = 27;
  446. var KEYCODE_LEFTARROW = 37;
  447. var KEYCODE_RIGHTARROW = 39;
  448. var keycode = event.keyCode;
  449. if (keycode === KEYCODE_ESC) {
  450. // Prevent bubbling so as to not affect other components on the page.
  451. event.stopPropagation();
  452. this.end();
  453. } else if (keycode === KEYCODE_LEFTARROW) {
  454. if (this.currentImageIndex !== 0) {
  455. this.changeImage(this.currentImageIndex - 1);
  456. } else if (this.options.wrapAround && this.album.length > 1) {
  457. this.changeImage(this.album.length - 1);
  458. }
  459. } else if (keycode === KEYCODE_RIGHTARROW) {
  460. if (this.currentImageIndex !== this.album.length - 1) {
  461. this.changeImage(this.currentImageIndex + 1);
  462. } else if (this.options.wrapAround && this.album.length > 1) {
  463. this.changeImage(0);
  464. }
  465. }
  466. };
  467. // Closing time. :-(
  468. Lightbox.prototype.end = function() {
  469. this.disableKeyboardNav();
  470. $(window).off('resize', this.sizeOverlay);
  471. this.$lightbox.fadeOut(this.options.fadeDuration);
  472. this.$overlay.fadeOut(this.options.fadeDuration);
  473. if (this.options.disableScrolling) {
  474. $('body').removeClass('lb-disable-scrolling');
  475. }
  476. };
  477. return new Lightbox();
  478. }));