Simple JavaScript gallery

Most drop-in HTML image galleries are bloated and very complicated. I tried to write a super simple and minimal HTML image gallery in JavaScript. It is written in less than 50 lines!

In some recent blog posts, I added quite a lot of images. So, I thought it would be nice, to be able to click on an image to view it full screen and then to scroll through all images on the page. I did not find a minimal script that did just that, all options were very bloated, so I just wrote my own slideshow script.

The script is so simple, that this blog post contains all the code, so you can take it, adapt it, and make it your own.

Example

An example can be found here: SIRUB.com

Features

  • click on any image on the page to view it full screen
  • use $\leftarrow$/$\rightarrow$ or k/j or h/l or a/d or w/s to flip through all images
  • hit Escape or q or tap anywhere to leave the gallery and return to the page

Installation

The installation is simple:

  • Just include the gallery.js file at the end of your html page
1
<script src="gallery.js"></script>
  • add this to your css stylesheet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#gallery {
    max-width: 100%;
    max-height: 100%;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border: 100rem solid black;
    background: white;
}
  • you do not have to change how you embed your images, all <img> tags are used for the gallery:
1
2
<img src="photo1.jpg" />
<img src="photo2.jpg" />

Source code

Here are the contents of gallery.js:

 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
/*
    Simple JavaScript Gallery v1.0
    by Desmond Kabus
    https://www.kabus.eu/blog/2019/05-26-simple-js-gallery.html
*/

const imgs = document.images;
var img_index_open = -1;

function close() {
    var gallery = document.getElementById("gallery");
    if ( gallery )
    { document.body.removeChild(gallery); }
    img_index_open = -1;
}

function open(i) {
    close();
    if( 0 <= i && i < imgs.length )
    {
        img_index_open = i;
        var gallery = imgs[img_index_open].cloneNode(true);
        gallery.style = "width:auto; height:auto;";
        gallery.id = "gallery";
        gallery.onclick = close;
        document.body.appendChild(gallery);
    }
}

for ( let i = 0; i < imgs.length; i++ ) {
    imgs[i].onclick = function(){ open(i) };
}

window.addEventListener("keydown", function (event) {
    if ( img_index_open < 0 || img_index_open >= imgs.length )
    { return; }
    else if ( ["Escape", "q"].includes(event.key) )
    { close(); }
    else if ( ["ArrowLeft","ArrowUp","h","k","w","a"].includes(event.key) )
    { open(img_index_open - 1); }
    else if ( [" ","ArrowRight","ArrowDown","l","j","s","d"].includes(event.key) )
    { open(img_index_open + 1); }
});
Desmond Kabus
Last updated on 2024-01-14 13:11 UTC+01