lg-hash.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*! lightgallery - v1.2.21 - 2016-06-28
  2. * http://sachinchoolur.github.io/lightGallery/
  3. * Copyright (c) 2016 Sachin N; Licensed Apache 2.0 */
  4. (function($, window, document, undefined) {
  5. 'use strict';
  6. var defaults = {
  7. hash: true
  8. };
  9. var Hash = function(element) {
  10. this.core = $(element).data('lightGallery');
  11. this.core.s = $.extend({}, defaults, this.core.s);
  12. if (this.core.s.hash) {
  13. this.oldHash = window.location.hash;
  14. this.init();
  15. }
  16. return this;
  17. };
  18. Hash.prototype.init = function() {
  19. var _this = this;
  20. var _hash;
  21. // Change hash value on after each slide transition
  22. _this.core.$el.on('onAfterSlide.lg.tm', function(event, prevIndex, index) {
  23. window.location.hash = 'lg=' + _this.core.s.galleryId + '&slide=' + index;
  24. });
  25. // Listen hash change and change the slide according to slide value
  26. $(window).on('hashchange.lg.hash', function() {
  27. _hash = window.location.hash;
  28. var _idx = parseInt(_hash.split('&slide=')[1], 10);
  29. // it galleryId doesn't exist in the url close the gallery
  30. if ((_hash.indexOf('lg=' + _this.core.s.galleryId) > -1)) {
  31. _this.core.slide(_idx, false, false);
  32. } else if (_this.core.lGalleryOn) {
  33. _this.core.destroy();
  34. }
  35. });
  36. };
  37. Hash.prototype.destroy = function() {
  38. if (!this.core.s.hash) {
  39. return;
  40. }
  41. // Reset to old hash value
  42. if (this.oldHash && this.oldHash.indexOf('lg=' + this.core.s.galleryId) < 0) {
  43. window.location.hash = this.oldHash;
  44. } else {
  45. if (history.pushState) {
  46. history.pushState('', document.title, window.location.pathname + window.location.search);
  47. } else {
  48. window.location.hash = '';
  49. }
  50. }
  51. this.core.$el.off('.lg.hash');
  52. };
  53. $.fn.lightGallery.modules.hash = Hash;
  54. })(jQuery, window, document);