From 57e925e4ac877906c07eb24b8663ac34606f9b31 Mon Sep 17 00:00:00 2001 From: Volpeon Date: Wed, 29 Dec 2021 20:20:17 +0100 Subject: Keyboard-friendly lightbox --- assets/css/components/_lightbox.scss | 2 +- content/lightbox.js | 50 +++++++++++++++++++++++++++++++----- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/assets/css/components/_lightbox.scss b/assets/css/components/_lightbox.scss index ece2b4b..b23943a 100644 --- a/assets/css/components/_lightbox.scss +++ b/assets/css/components/_lightbox.scss @@ -24,7 +24,7 @@ justify-content: center; width: 100%; height: 100%; - padding: 2em calc(3em + 1rem); + padding: 1em calc(3em + 1rem); transition: opacity .2s, visibility .2s; opacity: 0; diff --git a/content/lightbox.js b/content/lightbox.js index e57d37c..a3e3bc0 100644 --- a/content/lightbox.js +++ b/content/lightbox.js @@ -1,5 +1,7 @@ (() => { let currentIndex = 0; + let visible = false; + const mainEl = document.querySelector("main"); const lightboxEl = document.querySelector(".c-lightbox"); const lightboxBgEl = document.querySelector(".c-lightbox__bg"); @@ -10,26 +12,34 @@ const figureEls = Array.from(mainEl.querySelectorAll("figure")).map(el => el.querySelector("a")); const show = () => { + visible = true; lightboxEl.classList.add("is-shown"); } const hide = () => { + visible = false; lightboxEl.classList.remove("is-shown"); } const setIndex = (i) => { currentIndex = i; lightboxImgEl.src = figureEls[i].href; + lightboxPrevEl.classList.toggle("u-dn", i === 0); + lightboxNextEl.classList.toggle("u-dn", i === figureEls.length - 1); + }; + + const prev = () => { + setIndex(currentIndex === 0 ? currentIndex : currentIndex - 1); + }; + + const next = () => { + setIndex(currentIndex === figureEls.length - 1 ? currentIndex : currentIndex + 1); }; lightboxBgEl.addEventListener("click", hide); lightboxCloseEl.addEventListener("click", hide); - lightboxPrevEl.addEventListener("click", () => { - setIndex(currentIndex === 0 ? figureEls.length - 1 : currentIndex - 1); - }); - lightboxNextEl.addEventListener("click", () => { - setIndex(currentIndex === figureEls.length - 1 ? 0 : currentIndex + 1); - }); + lightboxPrevEl.addEventListener("click", prev); + lightboxNextEl.addEventListener("click", next); figureEls.forEach((figureEl, i) => { figureEl.addEventListener("click", e => { @@ -38,4 +48,32 @@ setIndex(i); }) }); + + window.addEventListener("keydown", e => { + if (e.defaultPrevented || !visible) { + return; + } + + switch (e.key) { + case "Left": + case "ArrowLeft": + prev(); + break; + + case "Right": + case "ArrowRight": + next(); + break; + + case "Esc": + case "Escape": + hide(); + break; + + default: + return; + } + + e.preventDefault(); + }, true); })(); -- cgit v1.2.3-70-g09d2