lightbox.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /*!
  2. * Lightbox v2.10.0
  3. * by Lokesh Dhakar
  4. *
  5. * More info:
  6. * http://lokeshdhakar.com/projects/lightbox2/
  7. *
  8. * Copyright 2007, 2018 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: '%1 / %2',
  41. alwaysShowNavOnTouchDevices: false,
  42. fadeDuration: 600,
  43. fitImagesInViewport: true,
  44. imageFadeDuration: 600,
  45. maxWidth: 800,
  46. maxHeight: 600,
  47. positionFromTop:150,
  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. $('<div id="lightboxOverlay" class="lightboxOverlay"></div><div id="lightbox" class="lightbox"><div class="lb-outerContainer"><div class="lb-container"><img class="lb-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" /><div class="lb-nav"><a class="lb-prev" href="" ></a><a class="lb-next" 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'));
  92. // Cache jQuery objects
  93. this.$lightbox = $('#lightbox');
  94. this.$overlay = $('#lightboxOverlay');
  95. this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
  96. this.$container = this.$lightbox.find('.lb-container');
  97. this.$image = this.$lightbox.find('.lb-image');
  98. this.$nav = this.$lightbox.find('.lb-nav');
  99. // Store css values for future lookup
  100. this.containerPadding = {
  101. top: parseInt(this.$container.css('padding-top'), 10),
  102. right: parseInt(this.$container.css('padding-right'), 10),
  103. bottom: parseInt(this.$container.css('padding-bottom'), 10),
  104. left: parseInt(this.$container.css('padding-left'), 10)
  105. };
  106. this.imageBorderWidth = {
  107. top: parseInt(this.$image.css('border-top-width'), 10),
  108. right: parseInt(this.$image.css('border-right-width'), 10),
  109. bottom: parseInt(this.$image.css('border-bottom-width'), 10),
  110. left: parseInt(this.$image.css('border-left-width'), 10)
  111. };
  112. // Attach event handlers to the newly minted DOM elements
  113. this.$overlay.hide().on('click', function() {
  114. self.end();
  115. return false;
  116. });
  117. this.$lightbox.hide().on('click', function(event) {
  118. if ($(event.target).attr('id') === 'lightbox') {
  119. self.end();
  120. }
  121. return false;
  122. });
  123. this.$outerContainer.on('click', function(event) {
  124. if ($(event.target).attr('id') === 'lightbox') {
  125. self.end();
  126. }
  127. return false;
  128. });
  129. this.$lightbox.find('.lb-prev').on('click', function() {
  130. if (self.currentImageIndex === 0) {
  131. self.changeImage(self.album.length - 1);
  132. } else {
  133. self.changeImage(self.currentImageIndex - 1);
  134. }
  135. return false;
  136. });
  137. this.$lightbox.find('.lb-next').on('click', function() {
  138. if (self.currentImageIndex === self.album.length - 1) {
  139. self.changeImage(0);
  140. } else {
  141. self.changeImage(self.currentImageIndex + 1);
  142. }
  143. return false;
  144. });
  145. /*
  146. Show context menu for image on right-click
  147. There is a div containing the navigation that spans the entire image and lives above of it. If
  148. you right-click, you are right clicking this div and not the image. This prevents users from
  149. saving the image or using other context menu actions with the image.
  150. To fix this, when we detect the right mouse button is pressed down, but not yet clicked, we
  151. set pointer-events to none on the nav div. This is so that the upcoming right-click event on
  152. the next mouseup will bubble down to the image. Once the right-click/contextmenu event occurs
  153. we set the pointer events back to auto for the nav div so it can capture hover and left-click
  154. events as usual.
  155. */
  156. this.$nav.on('mousedown', function(event) {
  157. if (event.which === 3) {
  158. self.$nav.css('pointer-events', 'none');
  159. self.$lightbox.one('contextmenu', function() {
  160. setTimeout(function() {
  161. this.$nav.css('pointer-events', 'auto');
  162. }.bind(self), 0);
  163. });
  164. }
  165. });
  166. this.$lightbox.find('.lb-loader, .lb-close').on('click', function() {
  167. self.end();
  168. return false;
  169. });
  170. };
  171. // Show overlay and lightbox. If the image is part of a set, add siblings to album array.
  172. Lightbox.prototype.start = function($link) {
  173. var self = this;
  174. var $window = $(window);
  175. $window.on('resize', $.proxy(this.sizeOverlay, this));
  176. $('select, object, embed').css({
  177. visibility: 'hidden'
  178. });
  179. this.sizeOverlay();
  180. this.album = [];
  181. var imageNumber = 0;
  182. function addToAlbum($link) {
  183. self.album.push({
  184. alt: $link.attr('data-alt'),
  185. link: $link.attr('href'),
  186. title: $link.attr('data-title') || $link.attr('title')
  187. });
  188. }
  189. // Support both data-lightbox attribute and rel attribute implementations
  190. var dataLightboxValue = $link.attr('data-lightbox');
  191. var $links;
  192. if (dataLightboxValue) {
  193. $links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
  194. for (var i = 0; i < $links.length; i = ++i) {
  195. addToAlbum($($links[i]));
  196. if ($links[i] === $link[0]) {
  197. imageNumber = i;
  198. }
  199. }
  200. } else {
  201. if ($link.attr('rel') === 'lightbox') {
  202. // If image is not part of a set
  203. addToAlbum($link);
  204. } else {
  205. // If image is part of a set
  206. $links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
  207. for (var j = 0; j < $links.length; j = ++j) {
  208. addToAlbum($($links[j]));
  209. if ($links[j] === $link[0]) {
  210. imageNumber = j;
  211. }
  212. }
  213. }
  214. }
  215. // Position Lightbox
  216. var top = $window.scrollTop() + this.options.positionFromTop;
  217. var left = $window.scrollLeft();
  218. this.$lightbox.css({
  219. top: top + 'px',
  220. left: left + 'px'
  221. }).fadeIn(this.options.fadeDuration);
  222. // Disable scrolling of the page while open
  223. if (this.options.disableScrolling) {
  224. $('html').addClass('lb-disable-scrolling');
  225. }
  226. this.changeImage(imageNumber);
  227. };
  228. // Hide most UI elements in preparation for the animated resizing of the lightbox.
  229. Lightbox.prototype.changeImage = function(imageNumber) {
  230. var self = this;
  231. this.disableKeyboardNav();
  232. var $image = this.$lightbox.find('.lb-image');
  233. this.$overlay.fadeIn(this.options.fadeDuration);
  234. $('.lb-loader').fadeIn('slow');
  235. this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
  236. this.$outerContainer.addClass('animating');
  237. // When image to show is preloaded, we send the width and height to sizeContainer()
  238. var preloader = new Image();
  239. preloader.onload = function() {
  240. var $preloader;
  241. var imageHeight;
  242. var imageWidth;
  243. var maxImageHeight;
  244. var maxImageWidth;
  245. var windowHeight;
  246. var windowWidth;
  247. $image.attr({
  248. 'alt': self.album[imageNumber].alt,
  249. 'src': self.album[imageNumber].link
  250. });
  251. $preloader = $(preloader);
  252. $image.width(preloader.width);
  253. $image.height(preloader.height);
  254. if (self.options.fitImagesInViewport) {
  255. // Fit image inside the viewport.
  256. // Take into account the border around the image and an additional 10px gutter on each side.
  257. windowWidth = $(window).width();
  258. windowHeight = $(window).height();
  259. maxImageWidth = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20;
  260. maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - 120;
  261. // Check if image size is larger then maxWidth|maxHeight in settings
  262. if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
  263. maxImageWidth = self.options.maxWidth;
  264. }
  265. if (self.options.maxHeight && self.options.maxHeight < maxImageWidth) {
  266. maxImageHeight = self.options.maxHeight;
  267. }
  268. // Is the current image's width or height is greater than the maxImageWidth or maxImageHeight
  269. // option than we need to size down while maintaining the aspect ratio.
  270. if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
  271. if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
  272. imageWidth = maxImageWidth;
  273. imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
  274. $image.width(imageWidth);
  275. $image.height(imageHeight);
  276. } else {
  277. imageHeight = maxImageHeight;
  278. imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
  279. $image.width(imageWidth);
  280. $image.height(imageHeight);
  281. }
  282. }
  283. }
  284. self.sizeContainer($image.width(), $image.height());
  285. };
  286. preloader.src = this.album[imageNumber].link;
  287. this.currentImageIndex = imageNumber;
  288. };
  289. // Stretch overlay to fit the viewport
  290. Lightbox.prototype.sizeOverlay = function() {
  291. this.$overlay
  292. .width($(document).width())
  293. .height($(document).height());
  294. };
  295. // Animate the size of the lightbox to fit the image we are showing
  296. Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
  297. var self = this;
  298. var oldWidth = this.$outerContainer.outerWidth();
  299. var oldHeight = this.$outerContainer.outerHeight();
  300. var newWidth = imageWidth + this.containerPadding.left + this.containerPadding.right + this.imageBorderWidth.left + this.imageBorderWidth.right;
  301. var newHeight = imageHeight + this.containerPadding.top + this.containerPadding.bottom + this.imageBorderWidth.top + this.imageBorderWidth.bottom;
  302. function postResize() {
  303. self.$lightbox.find('.lb-dataContainer').width(newWidth);
  304. self.$lightbox.find('.lb-prevLink').height(newHeight);
  305. self.$lightbox.find('.lb-nextLink').height(newHeight);
  306. self.showImage();
  307. }
  308. if (oldWidth !== newWidth || oldHeight !== newHeight) {
  309. this.$outerContainer.animate({
  310. width: newWidth,
  311. height: newHeight
  312. }, this.options.resizeDuration, 'swing', function() {
  313. postResize();
  314. });
  315. } else {
  316. postResize();
  317. }
  318. };
  319. // Display the image and its details and begin preload neighboring images.
  320. Lightbox.prototype.showImage = function() {
  321. this.$lightbox.find('.lb-loader').stop(true).hide();
  322. this.$lightbox.find('.lb-image').fadeIn(this.options.imageFadeDuration);
  323. this.updateNav();
  324. this.updateDetails();
  325. this.preloadNeighboringImages();
  326. this.enableKeyboardNav();
  327. };
  328. // Display previous and next navigation if appropriate.
  329. Lightbox.prototype.updateNav = function() {
  330. // Check to see if the browser supports touch events. If so, we take the conservative approach
  331. // and assume that mouse hover events are not supported and always show prev/next navigation
  332. // arrows in image sets.
  333. var alwaysShowNav = false;
  334. try {
  335. document.createEvent('TouchEvent');
  336. alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
  337. } catch (e) {}
  338. this.$lightbox.find('.lb-nav').show();
  339. if (this.album.length > 1) {
  340. if (this.options.wrapAround) {
  341. if (alwaysShowNav) {
  342. this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
  343. }
  344. this.$lightbox.find('.lb-prev, .lb-next').show();
  345. } else {
  346. if (this.currentImageIndex > 0) {
  347. this.$lightbox.find('.lb-prev').show();
  348. if (alwaysShowNav) {
  349. this.$lightbox.find('.lb-prev').css('opacity', '1');
  350. }
  351. }
  352. if (this.currentImageIndex < this.album.length - 1) {
  353. this.$lightbox.find('.lb-next').show();
  354. if (alwaysShowNav) {
  355. this.$lightbox.find('.lb-next').css('opacity', '1');
  356. }
  357. }
  358. }
  359. }
  360. };
  361. // Display caption, image number, and closing button.
  362. Lightbox.prototype.updateDetails = function() {
  363. var self = this;
  364. // Enable anchor clicks in the injected caption html.
  365. // Thanks Nate Wright for the fix. @https://github.com/NateWr
  366. if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
  367. this.album[this.currentImageIndex].title !== '') {
  368. var $caption = this.$lightbox.find('.lb-caption');
  369. if (this.options.sanitizeTitle) {
  370. $caption.text(this.album[this.currentImageIndex].title);
  371. } else {
  372. $caption.html(this.album[this.currentImageIndex].title);
  373. }
  374. $caption.fadeIn('fast')
  375. .find('a').on('click', function(event) {
  376. if ($(this).attr('target') !== undefined) {
  377. window.open($(this).attr('href'), $(this).attr('target'));
  378. } else {
  379. location.href = $(this).attr('href');
  380. }
  381. });
  382. }
  383. if (this.album.length > 1 && this.options.showImageNumberLabel) {
  384. var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
  385. this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
  386. } else {
  387. this.$lightbox.find('.lb-number').hide();
  388. }
  389. this.$outerContainer.removeClass('animating');
  390. this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function() {
  391. return self.sizeOverlay();
  392. });
  393. };
  394. // Preload previous and next images in set.
  395. Lightbox.prototype.preloadNeighboringImages = function() {
  396. if (this.album.length > this.currentImageIndex + 1) {
  397. var preloadNext = new Image();
  398. preloadNext.src = this.album[this.currentImageIndex + 1].link;
  399. }
  400. if (this.currentImageIndex > 0) {
  401. var preloadPrev = new Image();
  402. preloadPrev.src = this.album[this.currentImageIndex - 1].link;
  403. }
  404. };
  405. Lightbox.prototype.enableKeyboardNav = function() {
  406. $(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  407. };
  408. Lightbox.prototype.disableKeyboardNav = function() {
  409. $(document).off('.keyboard');
  410. };
  411. Lightbox.prototype.keyboardAction = function(event) {
  412. var KEYCODE_ESC = 27;
  413. var KEYCODE_LEFTARROW = 37;
  414. var KEYCODE_RIGHTARROW = 39;
  415. var keycode = event.keyCode;
  416. var key = String.fromCharCode(keycode).toLowerCase();
  417. if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
  418. this.end();
  419. } else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
  420. if (this.currentImageIndex !== 0) {
  421. this.changeImage(this.currentImageIndex - 1);
  422. } else if (this.options.wrapAround && this.album.length > 1) {
  423. this.changeImage(this.album.length - 1);
  424. }
  425. } else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
  426. if (this.currentImageIndex !== this.album.length - 1) {
  427. this.changeImage(this.currentImageIndex + 1);
  428. } else if (this.options.wrapAround && this.album.length > 1) {
  429. this.changeImage(0);
  430. }
  431. }
  432. };
  433. // Closing time. :-(
  434. Lightbox.prototype.end = function() {
  435. this.disableKeyboardNav();
  436. $(window).off('resize', this.sizeOverlay);
  437. this.$lightbox.fadeOut(this.options.fadeDuration);
  438. this.$overlay.fadeOut(this.options.fadeDuration);
  439. $('select, object, embed').css({
  440. visibility: 'visible'
  441. });
  442. if (this.options.disableScrolling) {
  443. $('html').removeClass('lb-disable-scrolling');
  444. }
  445. };
  446. return new Lightbox();
  447. }));