Fast, private email that's just for you. Try Fastmail free for up to 30 days.
I’ve been meaning to add a “lightbox” to this site since it launched so images can be clicked or tapped on to view them at a larger size, but because I don’t post photos here very often, I haven’t had much of an incentive.
A few days ago, we were wandering through the Marina District, taking photos and enjoying one of San Francisco’s warm, early September afternoons. We strolled along Marina Green and Yacht Harbor, then past the Palace of Fine Arts.
After getting home, I was pleased enough with a handful of the shots that I wanted to share, but I felt they were best appreciated at larger sizes.
I finally had an excuse to solve my lightbox situation!
There were several options, but I landed on Fullscreen Lightbox (fslightbox.js), primarily because it was lightweight, had minimal configuration, and was self-contained: no jQuery or other dependencies needed.
Installing it on my self-hosted Ghost blog was easy enough. Here’s what I did:
assets/js/
directory;default.hbs
to load the script (see below);Here’s the code I added to default.hbs
:
<script>
// Find all images on the page that match one of these selectors.
const images = document.querySelectorAll('.kg-image-card img, .kg-gallery-card img');
// Iterate over each image and wrap it in an `<a>` tag
// with a unique `data-fslightbox` attribute.
images.forEach((image, index) => {
const a = document.createElement('a');
a.setAttribute('data-fslightbox', 'img-' + index);
a.href = image.src;
image.parentNode.insertBefore(a, image);
a.appendChild(image);
});
</script>
<script defer src="{{asset 'js/fslightbox.js'}}"></script>
One note on this code. By default, fslightbox finds all images on the page and loads them into a single gallery. On a photography-focused site, that makes sense, but not so much here, where photos are specific to the articles they’re in.
Fortunately, it was an easy enough change. fslightbox groups together all elements with the same data-fslightbox
attribute. If they all have a unique identifier, each is considered a single-image gallery. So, instead of this:
images.forEach((image) => {
…
a.setAttribute('data-fslightbox', '');
…
}
I have this:
images.forEach((image, index) => {
…
a.setAttribute('data-fslightbox', 'img-' + index);
…
}
Et voilà! Every image on the page now has a unique identifier (data-fslightbox="img-0"
, data-fslightbox="img-1"
, etc.) so each image opens individually.
Here are three photos from our San Francisco stroll; click or tap on each one to expand it for better viewing.