I recently needed a simple image lightbox for one of my websites, however all the scripts I found online seemed overkill in that their file size were fairly large (as much as 60 KB), and some didn’t even lazy-load the images.
So I set about creating a lightweight lightbox script which does lazy-loads – i.e. the images get loaded only when clicked on, instead of on page load. The final script can be tested at http://www.tristanperry.com/lightweight-lightbox/ and you can see the source on GitHub.
Note: This article was written in late 2014, and works against jQuery V1. There’s a small tweak needed to work against JQuery V3.
Install instructions
- Ensure that JQuery (v1.x) is referenced
- Include the CSS (from Styles.css) and the Javascript (from Scripts.js) in the page(s) you want the lightbox to appear in.
- The JS can go anywhere on the page – in the <head> or within the <body> due to using JQuery’s document ready [the $(function() { notation seen in Scripts.js is shorthand for $( document ).ready() ]
- Include the two lightbox <div> elements at the end of the <body>:
<div id="lbox" style="display: none;">
<div id="lboxinner">
</div>
</div>
- Then simply add attributes class=”lboxImg” data-full-url=”/path/to/full/image” to any <img> tags to convert them into lightbox-ready images. When clicked, the image defined in data-full-url is loaded and displayed on the page.
- For example: <img src=”Homepage_thumb.jpg” class=”lboxImg” data-full-url=”Homepage_full.jpg” />
Making changes
This lightbox script is MIT licensed so feel free to make any changes to suit your needs. I only needed basic lightbox functionality and I didn’t need it to be overly visually appealing, something you might wish to change. Please feel free to push any improvements via Github although remember that the intention with this script is to make it lightweight with a low file-size footprint.