summaryrefslogtreecommitdiffstats
path: root/content/lightbox.js
blob: 4ec959db18d9f7c8f83aeec0dab1f30caddf4b79 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
(() => {
    let currentIndex = 0;
    let visible = false;

    const mainEl = document.querySelector("main");
    const lightboxEl = document.querySelector(".c-lightbox");
    const lightboxBgEl = lightboxEl.querySelector(".c-lightbox__bg");
    const lightboxCountEl = lightboxEl.querySelector(".c-lightbox__count");
    const lightboxCloseEl = lightboxEl.querySelector(".c-lightbox__close");
    const lightboxPrevEl = lightboxEl.querySelector(".c-lightbox__prev");
    const lightboxNextEl = lightboxEl.querySelector(".c-lightbox__next");
    const lightboxImgEl = lightboxEl.querySelector(".c-lightbox__img");
    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;
        lightboxCountEl.textContent = (i + 1) + " / " + figureEls.length;
        lightboxPrevEl.classList.toggle("u-dn", i === 0);
        lightboxNextEl.classList.toggle("u-dn", i === figureEls.length - 1);
    };

    const prev = () => {
        currentIndex === 0 ? void 0 : setIndex(currentIndex - 1);
    };

    const next = () => {
        currentIndex === figureEls.length - 1 ? void 0 : setIndex(currentIndex + 1);
    };

    lightboxBgEl.addEventListener("click", hide);
    lightboxCloseEl.addEventListener("click", hide);
    lightboxPrevEl.addEventListener("click", prev);
    lightboxNextEl.addEventListener("click", next);
    
    figureEls.forEach((figureEl, i) => {
        figureEl.addEventListener("click", e => {
            e.preventDefault();
            show();
            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);
})();