Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.13 KB | None | 0 0
  1. //
  2. // By Osvaldas Valutis, www.osvaldas.info
  3. // Available for use under the MIT License
  4. //
  5. (function ($, window, document) {
  6. 'use strict';
  7. // COMPONENTS //
  8. var $activityObject = $('<div/>')
  9. .attr('class','imagelightbox-loading')
  10. .append($('<div/>')),
  11. $arrowLeftObject = $('<button/>',{
  12. type: 'button',
  13. class: 'imagelightbox-arrow imagelightbox-arrow-left',
  14. html: '<'}),
  15. $arrowRightObject = $('<button/>',{
  16. type: 'button',
  17. class: 'imagelightbox-arrow imagelightbox-arrow-right',
  18. html: '>'}),
  19. $arrows = $arrowLeftObject.add($arrowRightObject),
  20. $captionObject = $('<div/>', {
  21. class: 'imagelightbox-caption',
  22. html: '&nbsp;'
  23. }),
  24. $buttonObject = $('<a/>', {
  25. class: 'imagelightbox-close',
  26. html: 'X'
  27. }),
  28. $overlayObject = $('<div/>', {
  29. class:'imagelightbox-overlay'
  30. }),
  31. $navItem = $('<a/>', {
  32. href:'#',
  33. class:'imagelightbox-navitem'
  34. }),
  35. $navObject = $('<div/>', {
  36. class: 'imagelightbox-nav'
  37. }),
  38. $wrapper = $('<div/>', {
  39. class: 'imagelightbox-wrapper'
  40. });
  41.  
  42. var cssTransitionSupport = function () {
  43. var s = document.body || document.documentElement;
  44. s = s.style;
  45. if (s.WebkitTransition === '') {
  46. return '-webkit-';
  47. }
  48. if (s.MozTransition === '') {
  49. return '-moz-';
  50. }
  51. if (s.OTransition === '') {
  52. return '-o-';
  53. }
  54. if (s.transition === '') {
  55. return '';
  56. }
  57. return false;
  58. },
  59.  
  60. hasCssTransitionSupport = cssTransitionSupport() !== false,
  61.  
  62. cssTransitionTranslateX = function (element, positionX, speed) {
  63. var options = {}, prefix = cssTransitionSupport();
  64. options[prefix + 'transform'] = 'translateX(' + positionX + ')';
  65. options[prefix + 'transition'] = prefix + 'transform ' + speed + 's linear';
  66. element.css(options);
  67. },
  68.  
  69. hasTouch = ( 'ontouchstart' in window ),
  70. hasPointers = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
  71. wasTouched = function (event) {
  72. if (hasTouch) {
  73. return true;
  74. }
  75.  
  76. if (!hasPointers || typeof event === 'undefined' || typeof event.pointerType === 'undefined') {
  77. return false;
  78. }
  79.  
  80. if (typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined') {
  81. if (event.MSPOINTER_TYPE_MOUSE !== event.pointerType) {
  82. return true;
  83. }
  84. }
  85. else if (event.pointerType !== 'mouse') {
  86. return true;
  87. }
  88.  
  89. return false;
  90. };
  91.  
  92. $.fn.imageLightbox = function (opts) {
  93. var options = $.extend({
  94. selector: 'a[data-imagelightbox]',
  95. id: 'imagelightbox',
  96. allowedTypes: 'png|jpg|jpeg|gif', // TODO make it work again
  97. animationSpeed: 250,
  98. activity: false,
  99. arrows: false,
  100. button: false,
  101. caption: false,
  102. enableKeyboard: true,
  103. lockBody: false,
  104. navigation: false,
  105. overlay: false,
  106. preloadNext: true,
  107. quitOnEnd: false,
  108. quitOnImgClick: false,
  109. quitOnDocClick: true,
  110. quitOnEscKey: true
  111. }, opts),
  112. _onStart = function () {
  113. if (options.arrows) {
  114. arrowsOn(this);
  115. }
  116. if (options.navigation) {
  117. navigationOn();
  118. }
  119. if (options.overlay) {
  120. overlayOn();
  121. }
  122. if (options.button) {
  123. closeButtonOn();
  124. }
  125. if (options.caption) {
  126. $wrapper.append($captionObject);
  127. }
  128. },
  129. _onLoadStart = function () {
  130. if (options.activity) {
  131. activityIndicatorOn();
  132. }
  133. if (options.caption) {
  134. captionReset();
  135. }
  136. },
  137. _onLoadEnd = function () {
  138. if (options.activity) {
  139. activityIndicatorOff();
  140. }
  141. if (options.arrows) {
  142. $arrows.css('display', 'block');
  143. }
  144. },
  145. _previousTarget = function () {
  146. var targetIndex = targets.index(target) - 1;
  147. if (targetIndex < 0) {
  148. if (options.quitOnEnd === true) {
  149. _quitImageLightbox();
  150. return false;
  151. }
  152. else {
  153. targetIndex = targets.length - 1;
  154. }
  155. }
  156. target = targets.eq(targetIndex);
  157. $wrapper.trigger('previous.ilb2');
  158. _loadImage(+1);
  159. },
  160. _nextTarget = function () {
  161. var targetIndex = targets.index(target) + 1;
  162. if (targetIndex >= targets.length) {
  163. if (options.quitOnEnd === true) {
  164. _quitImageLightbox();
  165. return false;
  166. }
  167. else {
  168. targetIndex = 0;
  169. }
  170. }
  171. target = targets.eq(targetIndex);
  172. $wrapper.trigger('next.ilb2');
  173. _loadImage(-1);
  174. },
  175. activityIndicatorOn = function () {
  176. $wrapper.append($activityObject);
  177. },
  178. activityIndicatorOff = function () {
  179. $('.imagelightbox-loading').remove();
  180. },
  181. overlayOn = function () {
  182. $wrapper.append($overlayObject);
  183. },
  184. closeButtonOn = function () {
  185. $buttonObject.appendTo($wrapper).on('click.ilb7', function () {
  186. _quitImageLightbox();
  187. return false;
  188. });
  189. },
  190. captionReset = function () {
  191. $captionObject.html('&nbsp;');
  192. if ($(target).data('ilb2-caption')) {
  193. $captionObject.html($(target).data('ilb2-caption'));
  194. } else if ($(target).find('img').length > 0) {
  195. $captionObject.html($(target).find('img').attr('alt'));
  196. }
  197. },
  198. navigationOn = function () {
  199. if (targets.length) {
  200. for (var i = 0; i < targets.length; i++) {
  201. $navObject.append($navItem.clone());
  202. }
  203. var $navItems = $navObject.children('a');
  204. $navItems.eq(targets.index(target)).addClass('active');
  205.  
  206. //
  207. $wrapper.on('previous.ilb2 next.ilb2', function () {
  208. $navItems.removeClass('active').eq(targets.index(target)).addClass('active');
  209. });
  210. $wrapper.append($navObject);
  211. ////
  212. $navObject
  213. .on('click.ilb7 touchend.ilb7', function () {
  214. return false;
  215. })
  216. .on('click.ilb7 touchend.ilb7', 'a', function () {
  217. var $this = $(this);
  218. if (targets.eq($this.index()).attr('href') !== $('.imagelightbox').attr('src')) {
  219. var tmpTarget = targets.eq($this.index());
  220. if (tmpTarget.length) {
  221. currentIndex = targets.index(target);
  222. target = tmpTarget;
  223. _loadImage($this.index() < currentIndex ? -1 : 1);
  224. }
  225. }
  226. $this.addClass('active').siblings().removeClass('active');
  227. });
  228. }
  229. },
  230. arrowsOn = function () {
  231. $wrapper.append($arrows);
  232. $arrows.on('click.ilb7 touchend.ilb7', function (e) {
  233. e.stopImmediatePropagation();
  234. e.preventDefault();
  235. if ($(this).hasClass('imagelightbox-arrow-left')) {
  236. _previousTarget();
  237. } else {
  238. _nextTarget();
  239. }
  240. return false;
  241. });
  242. },
  243. targetSet = '',
  244. targets = $([]),
  245. target = $(),
  246. image = $(),
  247. imageWidth = 0,
  248. imageHeight = 0,
  249. swipeDiff = 0,
  250. inProgress = false,
  251. currentIndex = 0,
  252.  
  253. isTargetValid = function (validImage) {
  254. var allowedTypes = options.allowedTypes;
  255.  
  256. //test that RegExp is restricted to disjunction format
  257. var isGoodRE = /^(?!\|)[\w\|]+(?!\|)$/.test(allowedTypes);
  258. //
  259. if (!isGoodRE) {
  260. //allowedTypes = 'png|jpg|jpeg|gif';
  261. return false;
  262. }
  263. //
  264. var URL = validImage.attr('href');
  265. var ext = parseURL(URL).pathname;
  266. var re = new RegExp(allowedTypes,'i');
  267. //
  268. var isAllowed = re.test(ext);
  269. // function by Cory LaViska
  270. function parseURL(url) {
  271. var parser = document.createElement('a'),
  272. searchObject = {},
  273. queries, split, i;
  274. // Let the browser do the work
  275. parser.href = url;
  276. // Convert query string to object
  277. queries = parser.search.replace(/^\?/, '').split('&');
  278. for( i = 0; i < queries.length; i++ ) {
  279. split = queries[i].split('=');
  280. searchObject[split[0]] = split[1];
  281. }
  282. return {
  283. protocol: parser.protocol,
  284. host: parser.host,
  285. hostname: parser.hostname,
  286. port: parser.port,
  287. pathname: parser.pathname,
  288. search: parser.search,
  289. searchObject: searchObject,
  290. hash: parser.hash
  291. };
  292. }
  293. return isAllowed;
  294. },
  295. // TODO make it work again
  296. // isTargetValid = function (element) {
  297. // var classic = $(element).prop('tagName').toLowerCase() === 'a' && ( new RegExp('.(' + options.allowedTypes + ')$', 'i') ).test($(element).attr('href'));
  298. // var html5 = $(element).attr('data-lightbox') !== undefined;
  299. // return classic || html5;
  300. // },
  301.  
  302. _setImage = function () {
  303. if (!image.length) {
  304. return true;
  305. }
  306. var captionHeight = $captionObject.outerHeight();
  307.  
  308. var screenWidth = $(window).width() * 0.8,
  309. wHeight = ((window.innerHeight) ? window.innerHeight : $(window).height()) - captionHeight,
  310. screenHeight = wHeight * 0.9,
  311. tmpImage = new Image();
  312.  
  313. tmpImage.src = image.attr('src');
  314. tmpImage.onload = function () {
  315. imageWidth = tmpImage.width;
  316. imageHeight = tmpImage.height;
  317.  
  318. if (imageWidth > screenWidth || imageHeight > screenHeight) {
  319. var ratio = imageWidth / imageHeight > screenWidth / screenHeight ? imageWidth / screenWidth : imageHeight / screenHeight;
  320. imageWidth /= ratio;
  321. imageHeight /= ratio;
  322. }
  323.  
  324. image.css({
  325. 'width': imageWidth + 'px',
  326. 'height': imageHeight + 'px',
  327. 'top': ( wHeight - imageHeight ) / 2 + 'px',
  328. 'left': ( $(window).width() - imageWidth ) / 2 + 'px'
  329. });
  330. };
  331. },
  332.  
  333. _loadImage = function (direction) {
  334. if (inProgress) {
  335. return false;
  336. }
  337.  
  338. if (image.length) {
  339. var params = {'opacity': 0};
  340. if (hasCssTransitionSupport) {
  341. cssTransitionTranslateX(image, ( 100 * direction ) - swipeDiff + 'px', options.animationSpeed / 1000);
  342. }
  343. else {
  344. params.left = parseInt(image.css('left')) + 100 * direction + 'px';
  345. }
  346. image.animate(params, options.animationSpeed, function () {
  347. _removeImage();
  348. });
  349. swipeDiff = 0;
  350. }
  351.  
  352. inProgress = true;
  353. _onLoadStart();
  354.  
  355. setTimeout(function () {
  356. var imgPath = target.attr('href');
  357. // if ( imgPath === undefined ) {
  358. // imgPath = target.attr( 'data-lightbox' );
  359. // }
  360. image = $('<img id="' + options.id + '" />')
  361. .attr('src', imgPath)
  362. .on('load.ilb7', function () {
  363. $wrapper.trigger('loaded.ilb2');
  364. var params = {'opacity': 1};
  365.  
  366. image.appendTo($wrapper);
  367. _setImage();
  368. image.css('opacity', 0);
  369. if (hasCssTransitionSupport) {
  370. cssTransitionTranslateX(image, -100 * direction + 'px', 0);
  371. setTimeout(function () {
  372. cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
  373. }, 50);
  374. } else {
  375. var imagePosLeft = parseInt(image.css('left'));
  376. params.left = imagePosLeft + 'px';
  377. image.css('left', imagePosLeft - 100 * direction + 'px');
  378. }
  379.  
  380. image.animate(params, options.animationSpeed, function () {
  381. inProgress = false;
  382. _onLoadEnd();
  383. });
  384. if (options.preloadNext) {
  385. var nextTarget = targets.eq(targets.index(target) + 1);
  386. if (!nextTarget.length) {
  387. nextTarget = targets.eq(0);
  388. }
  389. $('<img />').attr('src', nextTarget.attr('href'));
  390. }
  391. })
  392. .on('error.ilb7', function () {
  393. _onLoadEnd();
  394. });
  395.  
  396. var swipeStart = 0,
  397. swipeEnd = 0,
  398. imagePosLeft = 0;
  399.  
  400. image.on(hasPointers ? 'pointerup.ilb7 MSPointerUp.ilb7' : 'click.ilb7', function (e) {
  401. e.preventDefault();
  402. if (options.quitOnImgClick) {
  403. _quitImageLightbox();
  404. return false;
  405. }
  406. if (wasTouched(e.originalEvent)) {
  407. return true;
  408. }
  409. var posX = ( e.pageX || e.originalEvent.pageX ) - e.target.offsetLeft;
  410. if (imageWidth / 2 > posX) {
  411. _previousTarget();
  412. } else {
  413. _nextTarget();
  414. }
  415. })
  416. .on('touchstart.ilb7 pointerdown.ilb7 MSPointerDown.ilb7', function (e) {
  417. if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
  418. return true;
  419. }
  420. if (hasCssTransitionSupport) {
  421. imagePosLeft = parseInt(image.css('left'));
  422. }
  423. swipeStart = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
  424. })
  425. .on('touchmove.ilb7 pointermove.ilb7 MSPointerMove.ilb7', function (e) {
  426. if ((!hasPointers && e.type === 'pointermove') || !wasTouched(e.originalEvent) || options.quitOnImgClick) {
  427. return true;
  428. }
  429. e.preventDefault();
  430. swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
  431. swipeDiff = swipeStart - swipeEnd;
  432. if (hasCssTransitionSupport) {
  433. cssTransitionTranslateX(image, -swipeDiff + 'px', 0);
  434. } else {
  435. image.css('left', imagePosLeft - swipeDiff + 'px');
  436. }
  437. })
  438. .on('touchend.ilb7 touchcancel.ilb7 pointerup.ilb7 pointercancel.ilb7 MSPointerUp.ilb7 MSPointerCancel.ilb7', function (e) {
  439. if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
  440. return true;
  441. }
  442. if (Math.abs(swipeDiff) > 50) {
  443. if (swipeDiff < 0) {
  444. _previousTarget();
  445. } else {
  446. _nextTarget();
  447. }
  448. } else {
  449. if (hasCssTransitionSupport) {
  450. cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
  451. } else {
  452. image.animate({'left': imagePosLeft + 'px'}, options.animationSpeed / 2);
  453. }
  454. }
  455. });
  456.  
  457. }, options.animationSpeed + 100);
  458. },
  459. _removeImage = function () {
  460. if (!image.length) {
  461. return false;
  462. }
  463. image.remove();
  464. image = $();
  465. },
  466.  
  467. _openImageLightbox = function ($target) {
  468. if (inProgress) {
  469. return false;
  470. }
  471. inProgress = false;
  472. target = $target;
  473. _onStart();
  474. $('body').append($wrapper);
  475. if (options.lockBody) {
  476. $('body').addClass('imagelightbox-scroll-lock');
  477. }
  478. $wrapper.trigger('start.ilb2');
  479. _loadImage(0);
  480. },
  481.  
  482. _quitImageLightbox = function () {
  483. $wrapper.trigger('quit.ilb2');
  484. if (options.lockBody) {
  485. $('body').removeClass('imagelightbox-scroll-lock');
  486. }
  487. if (!image.length) {
  488. return false;
  489. }
  490. image.animate({'opacity': 0}, options.animationSpeed, function () {
  491. _removeImage();
  492. inProgress = false;
  493. targets = $([]);
  494. $wrapper.remove().find('*').remove();
  495. });
  496. },
  497.  
  498. _addTargets = function( newTargets ) {
  499. newTargets.on('click.ilb7', {set: targetSet}, function (e) {
  500. e.preventDefault();
  501. targetSet = $(e.currentTarget).data('imagelightbox');
  502. filterTargets();
  503. if (targets.length < 1) {
  504. _quitImageLightbox();
  505. } else {
  506. _openImageLightbox($(this));
  507. }
  508. });
  509. function filterTargets () {
  510. newTargets
  511. .filter(function () {
  512. return $(this).data('imagelightbox') === targetSet;
  513. })
  514. .filter(function () {
  515. return isTargetValid($(this));
  516. })
  517. .each(function () {
  518. targets = targets.add($(this));
  519. });
  520. }
  521. };
  522.  
  523. $(window).on('resize.ilb7', _setImage);
  524.  
  525. $(document).ready(function() {
  526. if (options.quitOnDocClick) {
  527. $(document).on(hasTouch ? 'touchend.ilb7' : 'click.ilb7', function (e) {
  528. if (image.length && !$(e.target).is(image)) {
  529. e.preventDefault();
  530. _quitImageLightbox();
  531. }
  532. });
  533. }
  534.  
  535. if (options.lockBody) {
  536. $(document).on('keydown.ilb7', function (e) {
  537. if (!image.length) {
  538. return true;
  539. }
  540. if([9,32,38,40].indexOf(e.which) > -1) {
  541. e.preventDefault();
  542. return false;
  543. }
  544. });
  545. }
  546.  
  547. if (options.enableKeyboard) {
  548. $(document).on('keyup.ilb7', function (e) {
  549. if (!image.length) {
  550. return true;
  551. }
  552. e.preventDefault();
  553. if ([27].indexOf(e.which) > -1 && options.quitOnEscKey) {
  554. _quitImageLightbox();
  555. }
  556. if ([37].indexOf(e.which) > -1) {
  557. _previousTarget();
  558. } else if ([39].indexOf(e.which) > -1) {
  559. _nextTarget();
  560. }
  561. });
  562. }
  563. });
  564.  
  565. $(document).off('click', options.selector);
  566.  
  567. _addTargets($(this));
  568.  
  569. this.addToImageLightbox = function(elements) {
  570. _addTargets(elements);
  571. };
  572.  
  573. this.loadPreviousImage = function () {
  574. _previousTarget();
  575. };
  576.  
  577. this.loadNextImage = function () {
  578. _nextTarget();
  579. };
  580.  
  581. this.quitImageLightbox = function () {
  582. _quitImageLightbox();
  583. return this;
  584. };
  585.  
  586. this.startImageLightbox = function () {
  587. $(this).trigger('click.ilb7');
  588. };
  589.  
  590. return this;
  591. };
  592. })(jQuery, window, document);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement