A simple JavaScript Lightbox without dependencies

by Jochem Kossen

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 * Photo gallery in JavaScript
  3 *
  4 * Copyright 2024 Jochem Kossen
  5 *
  6 * Permission is hereby granted, free of charge, to any person obtaining a
  7 * copy ofthis software and associated documentation files (the “Software”),
  8 * to deal in the Software without restriction, including without limitation
  9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 10 * and/or sell copies of the Software, and to permit persons to whom the
 11 * Software is furnished to do so, subject to the following conditions:
 12 *
 13 * The above copyright notice and this permission notice shall be included
 14 * in all copies or substantial portions of the Software.
 15 *
 16 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
 17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 22 * IN THE SOFTWARE.
 23 *
 24 */
 25
 26/**
 27 * Main script loop
 28 */
 29const main = function () {
 30  const galleries = document.getElementsByClassName("gallery");
 31
 32  for (let i = 0; i < galleries.length; i++) {
 33    const gallery = galleries[i];
 34    const lightbox = createLightbox();
 35    if (gallery instanceof HTMLElement) {
 36      createGallery(gallery, lightbox);
 37    }
 38  }
 39};
 40
 41/**
 42 * Create a Lightbox instance
 43 *
 44 * @returns {object}
 45 */
 46const createLightbox = function () {
 47  const lightbox = document.createElement("div");
 48  const lightboxContent = document.createElement("div");
 49  const img = document.createElement("img");
 50  const closeLink = document.createElement("a");
 51  const prevLink = document.createElement("a");
 52  const nextLink = document.createElement("a");
 53
 54  /** @type {function} */
 55  let onPrev;
 56
 57  /** @type {function} */
 58  let onNext;
 59
 60  closeLink.href = "#";
 61  closeLink.innerHTML = "&times;";
 62
 63  prevLink.href = "#";
 64  prevLink.innerHTML = "&#10094;";
 65
 66  nextLink.href = "#";
 67  nextLink.innerHTML = "&#10095;";
 68
 69  lightbox.id = "lightbox";
 70  lightbox.className = "lightbox";
 71
 72  lightbox.appendChild(closeLink);
 73  lightboxContent.appendChild(prevLink);
 74  lightboxContent.appendChild(img);
 75  lightboxContent.appendChild(nextLink);
 76  lightbox.appendChild(lightboxContent);
 77
 78  /**
 79   * @param {function} fn
 80   */
 81  const setOnPrev = (fn) => (onPrev = fn);
 82
 83  /**
 84   * @param {function} fn
 85   */
 86  const setOnNext = (fn) => (onNext = fn);
 87
 88  /**
 89   * @param {string} uri
 90   */
 91  const show = function (uri) {
 92    setImage(uri);
 93    lightbox.style.display = "block";
 94  };
 95
 96  const hide = function () {
 97    lightbox.style.display = "none";
 98  };
 99
100  /**
101   * @param {string} uri
102   */
103  const setImage = function (uri) {
104    img.src = uri;
105  };
106
107  /**
108   * Make the buttons in the lightbox work
109   */
110  const enableLightboxButtons = function () {
111    closeLink.addEventListener("click", (event) => {
112      event.preventDefault();
113      hide();
114    });
115
116    prevLink.addEventListener("click", (event) => {
117      event.preventDefault();
118      if (onPrev) {
119        onPrev();
120      }
121    });
122
123    nextLink.addEventListener("click", (event) => {
124      event.preventDefault();
125      if (onNext) {
126        onNext();
127      }
128    });
129
130    window.addEventListener("keydown", (event) => {
131      if (lightbox.style.display !== "block") {
132        return;
133      }
134
135      if (event.key === "ArrowLeft") {
136        if (onPrev) {
137          onPrev();
138        }
139      } else if (event.key === "ArrowRight") {
140        if (onNext) {
141          onNext();
142        }
143      } else if (event.key === "Escape" || event.key === "x") {
144        hide();
145      }
146    });
147  };
148
149  enableLightboxButtons();
150  document.body.appendChild(lightbox);
151
152  return { show, setOnPrev, setOnNext };
153};
154
155/**
156 * Create a Gallery instance
157 *
158 * @param {HTMLElement} element
159 * @param {object} lightbox
160 */
161const createGallery = function (element, lightbox) {
162  /** @type {Array.<HTMLElement>} */
163  const slides = [];
164
165  /** @type {number} */
166  let prevSlide = 0;
167
168  /** @type {number} */
169  let nextSlide = 1;
170
171  const findSlides = function () {
172    const thumbnails = element.getElementsByTagName("figure");
173    for (let i = 0; i < thumbnails.length; i++) {
174      slides.push(thumbnails[i]);
175    }
176  };
177
178  const enableLightbox = function () {
179    for (let i = 0; i < slides.length; i++) {
180      slides[i].firstElementChild?.addEventListener("click", (event) => {
181        event.preventDefault();
182        showLightbox(i);
183      });
184    }
185  };
186
187  /**
188   * @param {number} slideNr
189   */
190  const showLightbox = function (slideNr) {
191    prevSlide = slideNr <= 0 ? slides.length - 1 : slideNr - 1;
192    nextSlide = slideNr >= slides.length - 1 ? 0 : slideNr + 1;
193
194    const link = slides[slideNr].firstElementChild;
195
196    if (link instanceof HTMLAnchorElement) {
197      lightbox.show(link.href);
198    }
199  };
200
201  findSlides();
202
203  lightbox.setOnPrev(() => showLightbox(prevSlide));
204  lightbox.setOnNext(() => showLightbox(nextSlide));
205
206  enableLightbox();
207};
208
209/**
210 * Start up the galleries
211 */
212main();

HTML

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

CSS

 1div.gallery {
 2  display: flex;
 3  flex-wrap: wrap;
 4  gap: 1rem;
 5  justify-content: space-between;
 6  max-width: 1200px;
 7}
 8
 9div.gallery > figure {
10  flex: 27%;
11  margin: 0;
12  padding: 0;
13}
14
15div.gallery.two > figure {
16  flex: 47%;
17}
18
19.lightbox {
20  background-color: #000000ef;
21  color: #fafafa;
22  display: none;
23  font-size: 32px;
24  font-weight: 900;
25  height: 100%;
26  left: 0;
27  overflow: auto;
28  position: fixed;
29  top: 0;
30  width: 100%;
31  z-index: 1;
32}
33
34.lightbox a:link,
35.lightbox a:visited {
36  color: #ffffff;
37  text-align: center;
38  text-decoration: none;
39  width: 10%;
40}
41
42.lightbox > a:link,
43.lightbox > a:visited {
44  position: fixed;
45  right: 0px;
46  z-index: 2;
47}
48
49.lightbox > div {
50  align-items: center;
51  display: flex;
52  height: 100%;
53  justify-content: space-between;
54  width: 100%;
55}
56
57.lightbox img {
58  -webkit-animation: fadeIn 0.5s;
59  animation: fadeIn 0.5s;
60  max-height: 90%;
61  max-width: 80%;
62  width: auto;
63}
64/* Media queries */
65@media screen and (max-width: 800px) {
66  div.gallery > figure {
67    flex: 47%;
68  }
69}

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.