Lightbox
Open photos, video, YouTube, Vimeo, iframes and HTML in a fast lightbox with zoom, swipe, thumbnails and slideshow. Every option, custom buttons, keys, events.
Every item whose media link points at a large file opens in the lightbox. There is one shared lightbox per page. It is a native <dialog>, so it traps focus, closes with Esc, and gives focus back to the thumbnail you came from.
Turn it off for a whole grid with lightbox="false" or lightbox: { enabled: false }. Items then keep their links but do not open anything. The lightbox demo shows images, video and HTML slides together.
What each slide needs #
The grid image is the thumbnail. The slide is whatever the a.mb-media link points to. Its type is detected from the address, or you set it with data-mb-type:
| Type | Detected when | Notes |
|---|---|---|
image | The href ends in .jpg, .jpeg, .png, .gif, .webp, .avif or .svg. | The thumbnail is shown at once as a placeholder, then swapped for the large image once it has decoded. |
video | The href ends in .mp4, .webm, .ogv or .mov. | A native <video controls playsinline>. Set data-mb-poster for the poster image. |
youtube | A YouTube address (youtube.com/watch, youtu.be, /embed/, /shorts/). | Loaded from youtube-nocookie.com. The player is created only when the slide is shown and removed when it leaves. |
vimeo | A Vimeo address. | Loaded from player.vimeo.com with dnt=1. Same lifecycle as YouTube. |
iframe | Never detected: set data-mb-type="iframe". | Any page that allows embedding. Give a width and height or it is 16:9. |
html | The href is #some-id. | The content of that element (or of a <template>) is copied into a scrollable panel. |
link | Any other address. | The link is simply followed. No lightbox. |
<!-- image -->
<a class="mb-media" href="images/big.jpg" data-mb-width="1800" data-mb-height="1200">...</a>
<!-- video file with a poster -->
<a class="mb-media" href="clips/intro.mp4" data-mb-poster="clips/intro.jpg" data-mb-width="1280" data-mb-height="720">...</a>
<!-- YouTube and Vimeo -->
<a class="mb-media" href="https://www.youtube.com/watch?v=aqz-KE-bpKQ">...</a>
<a class="mb-media" href="https://vimeo.com/76979871">...</a>
<!-- any embeddable page -->
<a class="mb-media" href="https://example.com/viewer" data-mb-type="iframe" data-mb-width="1000" data-mb-height="700">...</a>
<!-- rich HTML from the same page -->
<a class="mb-media" href="#about-us">...</a>
<template id="about-us"><h2>About us</h2><p>Anything you like, even <a href="/contact">links</a>.</p></template>If an item uses a <div class="mb-media"> instead of a link, put the address in data-mb-src. data-mb-width and data-mb-height give the natural size of the media. They set the shape of video and iframes, and the zoom limit of images.
In JSON the same things go into media:
{ media: { type: 'youtube', src: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', caption: 'Long caption', poster: 'poster.jpg' } }Several slides in one item #
An item can open more than one slide: its main media first, then a list you put inside the item. The list is hidden, but stays in the page for search engines and for visitors without JavaScript.
<article class="mb-item" data-id="villa">
<a class="mb-media" href="villa-1.jpg"><img src="villa-1-thumb.jpg" width="720" height="480" alt="Villa"></a>
<div class="mb-content"><h3 class="mb-title">Villa Aurora</h3></div>
<ul class="mb-gallery" hidden>
<li><a href="villa-2.jpg" data-mb-srcset="villa-2-900.jpg 900w, villa-2.jpg 1800w" title="Kitchen">The open kitchen</a></li>
<li><a href="villa-3.jpg">Garden at dusk</a></li>
<li><a href="https://youtu.be/aqz-KE-bpKQ" data-mb-poster="tour.jpg">Video tour</a></li>
</ul>
</article>Each link takes the same attributes as the media link (data-mb-type, data-mb-width, data-mb-height, data-mb-srcset, data-mb-sizes, data-mb-poster) plus data-mb-thumb for the thumbnail strip. title is the slide title (the item title when missing). The caption is data-mb-caption, or the text of the link. In JSON:
{ id: 'villa', title: 'Villa Aurora', thumb: { src: 'villa-1-thumb.jpg', width: 720, height: 480 },
media: { src: 'villa-1.jpg', gallery: [
{ src: 'villa-2.jpg', srcset: 'villa-2-900.jpg 900w, villa-2.jpg 1800w', title: 'Kitchen', caption: 'The open kitchen' },
{ src: 'villa-3.jpg', caption: 'Garden at dusk' },
] } }How the slides are ordered depends on lightbox.itemGallery:
'inline'(default): the slides of every item form one sequence. After the last slide of an item comes the first slide of the next item. The counter and the thumbnail strip count slides.'isolated': opened from an item with a gallery, the lightbox holds only that item's slides, and wraps around inside them. Items without a gallery still flip through the whole grid.
Items that filtering or search hides take their slides with them. Clicking the tile always opens the first slide. A deep link can point at a slide: #portfolio?item=villa&slide=3 (1-based; links without slide still open the first one). Items with a gallery show a chip with the number of slides (galleryBadge: false removes it); its text comes from i18n.gallery ('{n} photos').
Captions #
The lightbox shows the item title and a caption under the slide. The caption is data-mb-caption (media.caption), or the item's description text when there is none. captions: false hides both.
Responsive images: srcset and sizes #
Give the large image several candidates and the browser picks the best one for the screen:
<a class="mb-media" href="images/big-1800.jpg"
data-mb-srcset="images/big-900.jpg 900w, images/big-1800.jpg 1800w, images/big-3600.jpg 3600w"
data-mb-sizes="100vw"
data-mb-width="3600" data-mb-height="2400">...</a>href stays as the fallback and the address used by Download (and by Share when deep links are off). sizes defaults to 100vw. In JSON use media: { src, srcset, sizes }. The thumbnail strip also works for thumbnails that only have a srcset.
Options #
Set them under lightbox:
grid.options = {
lightbox: {
loop: true,
thumbnails: true,
slideshow: { enabled: true, autoStart: false, interval: 5000 },
download: true,
motion: 'spring',
},
};| Option | Default | Meaning |
|---|---|---|
enabled | true | Turn the lightbox off for this grid. |
scope | 'filtered' | 'filtered' flips through what the visitor currently has (including items not loaded yet). 'all' flips through every item. |
loop | true | Wrap from the last slide to the first. Applies when there are more than two slides. |
counter | true | Show "3 / 12". |
captions | true | Show title and caption. |
thumbnails | true | A strip of thumbnails, with a button to show or hide it. It is hidden on screens under 600px tall. |
zoom | true | Allow zoom (button, double click or tap, wheel, pinch). |
fullscreen | true | Show the fullscreen button where the browser supports it. |
download | false | Show a download button for the current slide. |
share | false | Share the link to the open photo with the system share sheet, or copy it to the clipboard. The link is the page address with the grid's deep link (#portfolio?item=villa&slide=3), so the person who opens it lands on the same photo. If deep links for the lightbox are off, or the grid has no id, it shares the address of the image file instead. |
transition | 'slide' | 'slide' or 'fade' between slides. |
openAnimation | 'zoom' | 'zoom' grows the image from its thumbnail and shrinks it back on close. 'fade' fades. |
swipeToClose | true | Drag down to close. |
motion | 'spring' | 'spring' for physical motion that carries a flick, or 'ease' for plain eased animation. |
toolbar | null | null is the standard bar. See Toolbar. |
backdropClick | 'close' | 'close' closes on a tap on the empty stage. false does nothing there. |
idle | 2500 | Milliseconds of inactivity before the controls hide during a slideshow or in fullscreen. false never hides them. |
wheel | 'zoom' | What the mouse wheel does: 'zoom', 'slide' (one slide per gesture) or 'close'. Ctrl and wheel (trackpad pinch) always zooms. |
keyboard | true | true, false or an object that remaps keys. See Keyboard. |
itemGallery | 'inline' | 'inline' or 'isolated', see above. |
preload | 1 | Slides built and loaded on each side of the current one, from 0 to 5. |
slideshow.enabled | true | Show the play button. |
slideshow.autoStart | false | Start playing when the lightbox opens. |
slideshow.interval | 4000 | Milliseconds per slide. |
slideshow.pauseOnHover | false | Pause the progress bar while a mouse is over the stage. |
slideshow: false is a shorthand for slideshow: { enabled: false }, and lightbox: false turns the whole lightbox off.
Zoom, swipe and gestures #
- Zoom goes from 1 to 4 times, and never beyond twice the natural size of the image when
data-mb-widthanddata-mb-heightare known. - Double click or double tap zooms in, and again to zoom out. Pinch on touch screens. Drag to pan while zoomed, and a released pan keeps moving a little before it settles.
- Swipe sideways to change slide: the slide follows your finger and a flick carries on. Swiping is off while zoomed.
- Drag down to close, when
swipeToCloseis on. - The slideshow shows a progress bar. It pauses when you interact, when the tab is hidden and on video slides.
Toolbar #
The default top bar has the counter on the left and the buttons zoom, slideshow, fullscreen, download, share, thumbnails and close on the right. download and share only appear if their option is on. toolbar lets you choose and order them, and add your own:
grid.options = {
lightbox: {
toolbar: {
left: ['counter'],
right: [
'zoom',
'slideshow',
{
id: 'like',
label: 'Like this photo',
icon: 'check',
onClick: ({ index, slide, item, close, next, prev }) => {
console.log('liked', slide.title, 'at position', index);
next();
},
},
'download',
'close',
],
},
},
};- Known keys are
counter,zoom,slideshow,fullscreen,download,share,thumbsandclose. A repeated or unknown key is dropped. - A side you leave out keeps its default, and
[]empties it. - With an explicit toolbar, listing
downloadorshareis enough to turn them on.zoom: false,thumbnails: false,slideshow: falseandcounter: falsestill turn their feature off. - A custom button is a real
<button>.labelis its accessible name and tooltip (it defaults toid).iconis the name of a built-in icon (see the list in Skins and captions), or an SVG string, or short text. onClickreceives{ index, slide, item, close(), next(), prev() }.itemis the grid item, which includes itsdataandterms.- Keep
closein the list. Esc still works without it, but touch users need the button.
Because a function cannot be compared, the shared lightbox is rebuilt when you assign a new function in the toolbar config.
Keyboard #
| Key | Action |
|---|---|
| Right and left arrows | next and prev (swapped in right-to-left pages) |
| Home and End | first and last |
+ or = and - or _ | zoomIn and zoomOut |
0 | zoomReset |
| Space | slideshow (play or pause) |
f | fullscreen |
| Esc | Close (native dialog behaviour, always on) |
Remap with an object. Keys are KeyboardEvent.key values, and a value of null, false or 'none' disables a key. Available actions: next, prev, first, last, zoomIn, zoomOut, zoomReset, slideshow, fullscreen, close, none.
grid.options = { lightbox: { keyboard: { j: 'next', k: 'prev', ' ': null } } };
grid.options = { lightbox: { keyboard: false } }; // no shortcuts, Esc still closesEvents #
The grid element emits these (all bubble):
| Event | detail |
|---|---|
mb:open | { item, index }, when the lightbox starts to open |
mb:lightbox-ready | { item, index }, when the open animation has settled |
mb:change | { item, index }, when the slide changes |
mb:lightbox-slide-loaded | { item, index }, when a slide (also a preloaded neighbour) has loaded |
mb:lightbox-slide-error | { item, index }, when a slide failed to load |
mb:lightbox-zoom | { item, index, scale }, whenever the zoom of the current slide changes |
mb:lightbox-before-close | { item, index }. Cancelable |
mb:close | {}, after the lightbox closed |
Stop a close, for example to ask for confirmation:
grid.addEventListener('mb:lightbox-before-close', (e) => {
if (!confirm('Close the viewer?')) e.preventDefault();
});before-close is asked on every close by the visitor (button, Esc, backdrop click, swipe) and by closeLightbox(). It is not asked when the grid is destroyed. If it is prevented, the lightbox stays open and a drag springs back.
Open it from code #
grid.openLightbox(0); // by position among the openable items in scope
grid.openLightbox('stair'); // by item id
grid.closeLightbox();Opening writes item=<id> into the address when deep links are on, so a link to an open photo works. See Filtering and search.
Use the lightbox without a grid #
The lightbox is also exported on its own. Pass slides and an index:
<script src="assets/media-boxes/media-boxes.js"></script>
<button id="open">Open</button>
<script>
const lb = MediaBoxes.createLightbox({ loop: true, i18n: { close: 'Close' } });
document.getElementById('open').addEventListener('click', () => {
lb.open([
{ id: 'a', type: 'image', src: 'images/a-1600.jpg', width: 1600, height: 1067, title: 'First' },
{ id: 'b', type: 'youtube', src: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', title: 'A film' },
], 0);
});
lb.on('change', ({ index, slide }) => console.log(index, slide.title));
</script>The returned object has open(slides, index, { getOrigin }), close(), next(), prev(), goTo(i), update(slides), destroy(), isOpen, index, getSlide(), getZoom() and on(type, handler), which returns an unsubscribe function. The event types are open, change, close, ready, slideloaded, slideerror, zoom and beforeclose. A slide is { id, type, src, width, height, thumb, alt, title, caption, poster, srcset, sizes }.
Styling the lightbox #
The lightbox is always dark and lives outside the grid, as a child of <body>. To restyle it, target .mb-lightbox rather than the grid. See Theming.