image-modal.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. (function () {
  2. const tiles = document.getElementsByClassName('tile');
  3. const figures = document.getElementsByClassName('clickable-fig');
  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. image.alt = option.label;
  19. };
  20. function imgPrev() {
  21. var work = Number.parseInt(dialog.dataset.work);
  22. var variant = Number.parseInt(dialog.dataset.variant) - 1;
  23. while (variant == -1) {
  24. if (variant < 0) {
  25. work -= 1;
  26. if (work < 0) {
  27. work = figures.length - 1;
  28. }
  29. const datalist = figures[work].lastElementChild;
  30. variant = datalist.children.length - 1;
  31. }
  32. }
  33. updateImage(work, variant);
  34. };
  35. function imgNext() {
  36. var work = Number.parseInt(dialog.dataset.work);
  37. var variant = Number.parseInt(dialog.dataset.variant) + 1;
  38. while (variant >= figures[work].lastElementChild.children.length) {
  39. work += 1;
  40. if (work >= figures.length) {
  41. work = 0;
  42. }
  43. variant = 0;
  44. }
  45. updateImage(work, variant);
  46. };
  47. function imgClose() {
  48. dialog.close();
  49. dialog.className = "hidden"; // nedded for safari :man_shrugging:
  50. };
  51. for (var i = 0; i < tiles.length; i++) {
  52. (function (workIndex) {
  53. tiles[workIndex].addEventListener('click', function () {
  54. updateImage(workIndex, 0);
  55. dialog.showModal();
  56. dialog.className = "";
  57. });
  58. })(i);
  59. }
  60. document.addEventListener('keydown', function (ev) {
  61. if (dialog.open) {
  62. switch (ev.key) {
  63. case "ArrowLeft":
  64. imgPrev();
  65. break;
  66. case "ArrowRight":
  67. imgNext();
  68. break;
  69. case "Escape":
  70. imgClose();
  71. break;
  72. default:
  73. return;
  74. }
  75. }
  76. })
  77. prevButton.addEventListener('click', imgPrev);
  78. nextButton.addEventListener('click', imgNext);
  79. closeButton.addEventListener('click', imgClose);
  80. })();