image-modal.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. (function () {
  2. const tiles = document.getElementsByClassName('tile');
  3. const figures = document.getElementsByClassName('work-item');
  4. var dialog = document.getElementById('dialog-image-modal');
  5. var image = document.getElementById('modal-image');
  6. var closeButton = document.getElementById('close-modal');
  7. var prevButton = document.getElementById('img-prev');
  8. var nextButton = document.getElementById('img-next');
  9. function saveImageIndex(work, variant) {
  10. dialog.dataset.work = work.toString();
  11. dialog.dataset.variant = variant.toString();
  12. };
  13. function updateImage(work, variant) {
  14. saveImageIndex(work, variant);
  15. const figure = figures[work];
  16. const option = figure.lastElementChild.children[variant];
  17. image.src = option.value;
  18. };
  19. function imgPrev() {
  20. var work = Number.parseInt(dialog.dataset.work);
  21. var variant = Number.parseInt(dialog.dataset.variant) - 1;
  22. if (variant < 0) {
  23. work -= 1;
  24. if (work < 0) {
  25. work = figures.length - 1;
  26. }
  27. const datalist = figures[work].lastElementChild;
  28. variant = datalist.children.length - 1;
  29. }
  30. updateImage(work, variant);
  31. };
  32. function imgNext() {
  33. var work = Number.parseInt(dialog.dataset.work);
  34. var variant = Number.parseInt(dialog.dataset.variant) + 1;
  35. const datalist = figures[work].lastElementChild;
  36. if (variant >= datalist.children.length) {
  37. work += 1;
  38. if (work >= figures.length) {
  39. work = 0;
  40. }
  41. variant = 0;
  42. }
  43. updateImage(work, variant);
  44. };
  45. function imgClose() {
  46. dialog.close();
  47. dialog.className = "hidden"; // nedded for safari :man_shrugging:
  48. };
  49. for (var i = 0; i < tiles.length; i++) {
  50. (function (workIndex) {
  51. tiles[workIndex].addEventListener('click', function () {
  52. updateImage(workIndex, 0);
  53. dialog.showModal();
  54. dialog.className = "";
  55. });
  56. })(i);
  57. }
  58. document.addEventListener('keydown', function (ev) {
  59. if (dialog.open) {
  60. switch (ev.key) {
  61. case "ArrowLeft":
  62. imgPrev();
  63. break;
  64. case "ArrowRight":
  65. imgNext();
  66. break;
  67. case "Escape":
  68. imgClose();
  69. break;
  70. default:
  71. return;
  72. }
  73. }
  74. })
  75. prevButton.addEventListener('click', imgPrev);
  76. nextButton.addEventListener('click', imgNext);
  77. closeButton.addEventListener('click', imgClose);
  78. })();