lg-hash.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*! lg-hash - v1.0.0 - 2016-09-20
  2. * http://sachinchoolur.github.io/lightGallery
  3. * Copyright (c) 2016 Sachin N; Licensed GPLv3 */
  4. (function (root, factory) {
  5. if (typeof define === 'function' && define.amd) {
  6. // AMD. Register as an anonymous module unless amdModuleId is set
  7. define([], function () {
  8. return (factory());
  9. });
  10. } else if (typeof exports === 'object') {
  11. // Node. Does not work with strict CommonJS, but
  12. // only CommonJS-like environments that support module.exports,
  13. // like Node.
  14. module.exports = factory();
  15. } else {
  16. factory();
  17. }
  18. }(this, function () {
  19. (function($, window, document, undefined) {
  20. 'use strict';
  21. var defaults = {
  22. hash: true
  23. };
  24. var Hash = function(element) {
  25. this.core = $(element).data('lightGallery');
  26. this.core.s = $.extend({}, defaults, this.core.s);
  27. if (this.core.s.hash) {
  28. this.oldHash = window.location.hash;
  29. this.init();
  30. }
  31. return this;
  32. };
  33. Hash.prototype.init = function() {
  34. var _this = this;
  35. var _hash;
  36. // Change hash value on after each slide transition
  37. _this.core.$el.on('onAfterSlide.lg.tm', function(event, prevIndex, index) {
  38. window.location.hash = 'lg=' + _this.core.s.galleryId + '&slide=' + index;
  39. });
  40. // Listen hash change and change the slide according to slide value
  41. $(window).on('hashchange.lg.hash', function() {
  42. _hash = window.location.hash;
  43. var _idx = parseInt(_hash.split('&slide=')[1], 10);
  44. // it galleryId doesn't exist in the url close the gallery
  45. if ((_hash.indexOf('lg=' + _this.core.s.galleryId) > -1)) {
  46. _this.core.slide(_idx, false, false);
  47. } else if (_this.core.lGalleryOn) {
  48. _this.core.destroy();
  49. }
  50. });
  51. };
  52. Hash.prototype.destroy = function() {
  53. if (!this.core.s.hash) {
  54. return;
  55. }
  56. // Reset to old hash value
  57. if (this.oldHash && this.oldHash.indexOf('lg=' + this.core.s.galleryId) < 0) {
  58. window.location.hash = this.oldHash;
  59. } else {
  60. if (history.pushState) {
  61. history.pushState('', document.title, window.location.pathname + window.location.search);
  62. } else {
  63. window.location.hash = '';
  64. }
  65. }
  66. this.core.$el.off('.lg.hash');
  67. };
  68. $.fn.lightGallery.modules.hash = Hash;
  69. })(jQuery, window, document);
  70. }));