lightbox.js 18 KB

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