Simple JavaScript Gallery

Desmond Kabus

2019-05-26 19:42

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

Here is a small example gallery:

Features

Installation

The installation is simple:

<script src="gallery.js"></script>
#gallery {
    max-width: 100%;
    max-height: 100%;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border: 100rem solid black;
    background: white;
}
<img src="photo1.jpg" />
<img src="photo2.jpg" />

Source code

Here are the contents of gallery.js:

/*
    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); }
});