Displaying images in a lightbox is an attractive way to show high-resolution versions of images when a user clicks a thumbnail. This method requires less than 50 lines of Javascript and CSS, does not require any libraries, and degrades gracefully for users with old browsers.
HTML
This method assumes that your thumbnails follow this format. Only the class
and href
attributes of the anchor
tag are used by the Javascript, so you can have as much additional code as you would like.
<a href="[high-resolution URI]" class="thumbnail"> <img> </a>
In addition, you need to have this code somewhere within the body
tag on your page:
<div id="lightbox"></div>
Javascript
This code works by adding two event listeners:
- The first event listener finds all the instances of links with the
thumbnail
class. The event listener checks for clicks on those links. If a click is registered, it suppresses going directly to the target of that link. Instead, it inserts an image into the lightboxdiv
tag, and displays the lightbox. - The second event listener hides the lightbox when clicked. This ensures that the user can close the lightbox by clicking anywhere on the page.
Because the thumbnail images may take a while to load, we can’t use the window.onload
function, as this doesn’t trigger until all page elements are loaded. Instead, we use a third event listener that only checks whether the HTML itself has loaded.
document.addEventListener('DOMContentLoaded', function() { var thumbnails = document.querySelectorAll('.thumbnail'); var lightbox = document.querySelector('#lightbox'); // Lightbox listener lightbox.addEventListener('click', function() { lightbox.innerHTML = null; lightbox.style.display = 'none'; }, false); // Thumbnail listener for(var i = 0, len = thumbnails.length | 0; i < len; i++) { thumbnails[i].addEventListener('click', function(e) { e.preventDefault(); lightbox.innerHTML = '<img src="' + this.href + '">'; lightbox.style.display = 'flex'; }.bind({href: thumbnails[i].href}), false); } });
CSS
The CSS is largely presentational. The only code needed to make the lightbox work is #lightbox{display: none;}
, though this would not make for a very attractive lightbox.
#lightbox { align-items: center; background-color: rgba(0, 0, 0, 0.75); display: none; height: 100%; justify-content: center; left: 0; position: fixed; text-align: center; top: 0; width: 100%; } #lightbox img { border: 25px solid #fff; max-height: calc(100% - 90px); max-width: calc(100% - 90px); }