A simple JavaScript Lightbox without dependencies

by Jochem Kossen in articles

Contents

TLDR

Abstract

Recently I got back into photography and wanted to show my photos on this website. So I searched the web for a script which would show large versions of the photos on a dark overlay without leaving the page. It should be easy to integrate into websites and pages should still be visible when the user has no JavaScript enabled. And as a rule, I also like smallish pieces of code. Most scripts that I found online consisted of many lines of code, probably because they were developed in a time when browser engines were far less compliant than those of today. Some also required multiple dependencies. And then there were those that lacked a feature I wanted to support: having multiple galleries on a single page.

Given all the possibilities web browsers nowadays give us I didn’t think it would be that hard coding this myself without using dependencies.

W3Schools (♥ you) has a nice little tutorial on how to get to the basics of a Lightbox done.

Starting from that I built a simple image gallery script that I use on this website.

You can see it in action in my IJssel Highwater 2024 and Litterland galleries.

Features

The Code

This is the version from the time of writing this article. It currently consists of 200-ish lines of code, that’s including JSDoc comments.

The JavaScript code consists essentially of two factory functions. One for the gallery to find the images, the other for the lightbox to show the large versions of the image.

Then there’s a main() function which loads everything.

It searches for HTML elements with the class gallery. For each such element, it searches <figure> elements with an image link in it. The lightbox will show the href of the <a href="...">. So when JavaScript is disabled, the links will still work.

Download the JavaScript code here: photo.js

JavaScript

  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
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
 * Photo gallery in JavaScript
 *
 * Copyright 2024 Jochem Kossen
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy ofthis software and associated documentation files (the “Software”),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 */

/**
 * Main script loop
 */
const main = function () {
  const galleries = document.getElementsByClassName("gallery");

  for (let i = 0; i < galleries.length; i++) {
    const gallery = galleries[i];
    const lightbox = createLightbox();
    if (gallery instanceof HTMLElement) {
      createGallery(gallery, lightbox);
    }
  }
};

/**
 * Create a Lightbox instance
 *
 * @returns {object}
 */
const createLightbox = function () {
  const lightbox = document.createElement("div");
  const lightboxContent = document.createElement("div");
  const img = document.createElement("img");
  const closeLink = document.createElement("a");
  const prevLink = document.createElement("a");
  const nextLink = document.createElement("a");

  /** @type {function} */
  let onPrev;

  /** @type {function} */
  let onNext;

  closeLink.href = "#";
  closeLink.innerHTML = "&times;";

  prevLink.href = "#";
  prevLink.innerHTML = "&#10094;";

  nextLink.href = "#";
  nextLink.innerHTML = "&#10095;";

  lightbox.id = "lightbox";
  lightbox.className = "lightbox";

  lightbox.appendChild(closeLink);
  lightboxContent.appendChild(prevLink);
  lightboxContent.appendChild(img);
  lightboxContent.appendChild(nextLink);
  lightbox.appendChild(lightboxContent);

  /**
   * @param {function} fn
   */
  const setOnPrev = (fn) => (onPrev = fn);

  /**
   * @param {function} fn
   */
  const setOnNext = (fn) => (onNext = fn);

  /**
   * @param {string} uri
   */
  const show = function (uri) {
    setImage(uri);
    lightbox.style.display = "block";
  };

  const hide = function () {
    lightbox.style.display = "none";
  };

  /**
   * @param {string} uri
   */
  const setImage = function (uri) {
    img.src = uri;
  };

  /**
   * Make the buttons in the lightbox work
   */
  const enableLightboxButtons = function () {
    closeLink.addEventListener("click", (event) => {
      event.preventDefault();
      hide();
    });

    prevLink.addEventListener("click", (event) => {
      event.preventDefault();
      if (onPrev) {
        onPrev();
      }
    });

    nextLink.addEventListener("click", (event) => {
      event.preventDefault();
      if (onNext) {
        onNext();
      }
    });

    window.addEventListener("keydown", (event) => {
      if (lightbox.style.display !== "block") {
        return;
      }

      if (event.key === "ArrowLeft") {
        if (onPrev) {
          onPrev();
        }
      } else if (event.key === "ArrowRight") {
        if (onNext) {
          onNext();
        }
      } else if (event.key === "Escape" || event.key === "x") {
        hide();
      }
    });
  };

  enableLightboxButtons();
  document.body.appendChild(lightbox);

  return { show, setOnPrev, setOnNext };
};

/**
 * Create a Gallery instance
 *
 * @param {HTMLElement} element
 * @param {object} lightbox
 */
const createGallery = function (element, lightbox) {
  /** @type {Array.<HTMLElement>} */
  const slides = [];

  /** @type {number} */
  let prevSlide = 0;

  /** @type {number} */
  let nextSlide = 1;

  const findSlides = function () {
    const thumbnails = element.getElementsByTagName("figure");
    for (let i = 0; i < thumbnails.length; i++) {
      slides.push(thumbnails[i]);
    }
  };

  const enableLightbox = function () {
    for (let i = 0; i < slides.length; i++) {
      slides[i].firstElementChild?.addEventListener("click", (event) => {
        event.preventDefault();
        showLightbox(i);
      });
    }
  };

  /**
   * @param {number} slideNr
   */
  const showLightbox = function (slideNr) {
    prevSlide = slideNr <= 0 ? slides.length - 1 : slideNr - 1;
    nextSlide = slideNr >= slides.length - 1 ? 0 : slideNr + 1;

    const link = slides[slideNr].firstElementChild;

    if (link instanceof HTMLAnchorElement) {
      lightbox.show(link.href);
    }
  };

  findSlides();

  lightbox.setOnPrev(() => showLightbox(prevSlide));
  lightbox.setOnNext(() => showLightbox(nextSlide));

  enableLightbox();
};

/**
 * Start up the galleries
 */
main();

HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<div class="gallery">
  <figure>
    <a href="jpg-1280/DSCF8660-1280.jpg">
      <img src="jpg-500/DSCF8660-500.jpg" alt="IJssel" />
    </a>
  </figure>

  <figure>
    <a href="jpg-1280/DSCF8663-1280.jpg">
      <img src="jpg-500/DSCF8663-500.jpg" alt="IJssel" />
    </a>
  </figure>

  <figure>
    <a href="jpg-1280/DSCF8672-1280.jpg">
      <img src="jpg-500/DSCF8672-500.jpg" alt="IJssel" />
    </a>
  </figure>
</div>

CSS

 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
div.gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  justify-content: space-between;
  max-width: 1200px;
}

div.gallery > figure {
  flex: 27%;
  margin: 0;
  padding: 0;
}

div.gallery.two > figure {
  flex: 47%;
}

.lightbox {
  background-color: #000000ef;
  color: #fafafa;
  display: none;
  font-size: 32px;
  font-weight: 900;
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1;
}

.lightbox a:link,
.lightbox a:visited {
  color: #ffffff;
  text-align: center;
  text-decoration: none;
  width: 10%;
}

.lightbox > a:link,
.lightbox > a:visited {
  position: fixed;
  right: 0px;
  z-index: 2;
}

.lightbox > div {
  align-items: center;
  display: flex;
  height: 100%;
  justify-content: space-between;
  width: 100%;
}

.lightbox img {
  -webkit-animation: fadeIn 0.5s;
  animation: fadeIn 0.5s;
  max-height: 90%;
  max-width: 80%;
  width: auto;
}
/* Media queries */
@media screen and (max-width: 800px) {
  div.gallery > figure {
    flex: 47%;
  }
}

Most recent version

The above download link gives you the version at the time of writing this article. The most recent version in Git can be found at Codeberg.