There are many lightbox libraries around, but many of them have a lot of features you may not need. As a result, they make you ship a lot of redundant code, and your website will use more bandwith than it probably should, resulting in higher energy usage and CO2 emissions. Materra Lightbox is a super simple photo lightbox that tries to be as small and lightweight as possible. A larger, more powerful library is, of course, very convenient for you as a developer. But there is a planet at stake, so if you do not need those features, using this library might be worth considering.
1. Via NPM
npm install materra-lightbox
After installing, you can import the script like this:
import MaterraLightbox from 'materra-lightbox';
2. From CDN
3. Download ZIP
Alternatively, you can download the package and include the following in your web page:
4. Native ES module
If you want to use Materra Lightbox as a native ES module, you do not need to add a
<script> tag for it. Instead, you can import it directly from your JS code:
import MaterraLightbox from 'dist/materra-lighbox.esm.min.js';
Or from CDN:
import MaterraLightbox from 'https://unpkg.com/materra-lightbox/dist/materra-lighbox.esm.min.js';
1. The HTML part
For each image you want to show up in the lightbox, you need to create a link to that image.
<a class="item" href="/path/to-image-1.jpg" data-alt="Description"> <a class="item" href="/path/to-image-2.jpg" data-alt="Description"> <a class="item" href="/path/to-image-3.jpg" data-alt="Description">
As you can see, you can give each link a
data-alt attribute. The value of this attribute will be used as alt text for images in the lightbox.
Initializing the lightbox is easy:
const lightbox = new MaterraLightbox('.item');
Given the above line of code, Materra Lightbox will look for all links with a
3. The CSS part
In order for the lightbox to look good, you need to include its CSS. How this is done depends on the way you use it.
If you use a module bundler that can compile CSS, you can import it from your JS code:
Otherwise, you will need to create a
<link> tag for it:
<link rel="stylesheet" href="dist/materra-lightbox.css">
Or from CDN:
<link rel="stylesheet" href="https://unpkg.com/materra-lightbox/dist/materra-lightbox.css">
Materra Lightbox exposes a simple API to help you make it do some things.
The method names should be self-explanatory. The
goTo() methods allow you to specify a slide to go to. It is a zero-based index, so the first slide has index 0.
The icons used in the lightbox were taken from the magnificent Feather icon set.