load-photoswipe.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. Put this file in /static/js/load-photoswipe.js
  3. Documentation and licence at https://github.com/liwenyip/hugo-easy-gallery/
  4. */
  5. /* TODO: Make the share function work */
  6. $( document ).ready(function() {
  7. /*
  8. Initialise Photoswipe
  9. */
  10. var items = []; // array of slide objects that will be passed to PhotoSwipe()
  11. // for every figure element on the page:
  12. $('figure').each( function() {
  13. if ($(this).attr('class') == 'no-photoswipe') return true; // ignore any figures where class="no-photoswipe"
  14. // get properties from child a/img/figcaption elements,
  15. var $figure = $(this),
  16. $a = $figure.find('a'),
  17. $img = $figure.find('img'),
  18. $title = $img.attr('alt'),
  19. $msrc = $img.attr('src');
  20. // if data-size on <a> tag is set, read it and create an item
  21. if ($a.data('size')) {
  22. $src = $a.attr('href');
  23. var $size = $a.data('size').split('x');
  24. var item = {
  25. src : $src,
  26. w : $size[0],
  27. h : $size[1],
  28. title : $title,
  29. msrc : $msrc
  30. };
  31. //console.log("Using pre-defined dimensions for " + $src);
  32. // if not, set temp default size then load the image to check actual size
  33. } else {
  34. var item = {
  35. src : $msrc,
  36. w : 800, // temp default size
  37. h : 600, // temp default size
  38. title : $title,
  39. msrc : $msrc
  40. };
  41. //console.log("Using default dimensions for " + $msrc);
  42. // load the image to check its dimensions
  43. // update the item as soon as w and h are known (check every 30ms)
  44. var img = new Image();
  45. img.src = $msrc;
  46. var wait = setInterval(function() {
  47. var w = img.naturalWidth,
  48. h = img.naturalHeight;
  49. if (w && h) {
  50. clearInterval(wait);
  51. item.w = w;
  52. item.h = h;
  53. //console.log("Got actual dimensions for " + img.src);
  54. }
  55. }, 30);
  56. }
  57. // Save the index of this image then add it to the array
  58. var index = items.length;
  59. items.push(item);
  60. // Event handler for click on a figure
  61. $figure.on('click', function(event) {
  62. event.preventDefault(); // prevent the normal behaviour i.e. load the <a> hyperlink
  63. // Get the PSWP element and initialise it with the desired options
  64. var $pswp = $('.pswp')[0];
  65. var options = {
  66. index: index,
  67. bgOpacity: 0.8,
  68. showHideOpacity: true
  69. }
  70. new PhotoSwipe($pswp, PhotoSwipeUI_Default, items, options).init();
  71. });
  72. });
  73. });