image-modal.js 2.7 KB

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