2019-05-26 19:42 UTC+02
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.
Here is a small example gallery:
k
/j
or h
/l
or a
/d
or w
/s
to flip through all imagesEscape
or q
or tap anywhere to leave the gallery and return to the pageThe installation is simple:
gallery.js
file at the end of your html
page<script src="gallery.js"></script>
css
stylesheet:#gallery {
max-width: 100%;
max-height: 100%;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border: 100rem solid black;
background: white;
}
<img>
tags are used for the gallery:<img src="photo1.jpg" />
<img src="photo2.jpg" />
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); }
{ = -1;
img_index_open
}
function open(i) {
close();
if( 0 <= i && i < imgs.length )
{= i;
img_index_open var gallery = imgs[img_index_open].cloneNode(true);
.style = "width:auto; height:auto;";
gallery.id = "gallery";
gallery.onclick = close;
gallerydocument.body.appendChild(gallery);
}
}
for ( let i = 0; i < imgs.length; i++ ) {
.onclick = function(){ open(i) };
imgs[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); }
{ ; })