DocumentationLightbox

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:

TypeDetected whenNotes
imageThe 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.
videoThe href ends in .mp4, .webm, .ogv or .mov.A native <video controls playsinline>. Set data-mb-poster for the poster image.
youtubeA 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.
vimeoA Vimeo address.Loaded from player.vimeo.com with dnt=1. Same lifecycle as YouTube.
iframeNever detected: set data-mb-type="iframe".Any page that allows embedding. Give a width and height or it is 16:9.
htmlThe href is #some-id.The content of that element (or of a <template>) is copied into a scrollable panel.
linkAny other address.The link is simply followed. No lightbox.
html
<!-- 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:

js
{ 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.

html
<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:

js
{ 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:

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:

html
<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:

js
grid.options = {
  lightbox: {
    loop: true,
    thumbnails: true,
    slideshow: { enabled: true, autoStart: false, interval: 5000 },
    download: true,
    motion: 'spring',
  },
};
OptionDefaultMeaning
enabledtrueTurn 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.
looptrueWrap from the last slide to the first. Applies when there are more than two slides.
countertrueShow "3 / 12".
captionstrueShow title and caption.
thumbnailstrueA strip of thumbnails, with a button to show or hide it. It is hidden on screens under 600px tall.
zoomtrueAllow zoom (button, double click or tap, wheel, pinch).
fullscreentrueShow the fullscreen button where the browser supports it.
downloadfalseShow a download button for the current slide.
sharefalseShare 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.
swipeToClosetrueDrag down to close.
motion'spring''spring' for physical motion that carries a flick, or 'ease' for plain eased animation.
toolbarnullnull is the standard bar. See Toolbar.
backdropClick'close''close' closes on a tap on the empty stage. false does nothing there.
idle2500Milliseconds 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.
keyboardtruetrue, false or an object that remaps keys. See Keyboard.
itemGallery'inline''inline' or 'isolated', see above.
preload1Slides built and loaded on each side of the current one, from 0 to 5.
slideshow.enabledtrueShow the play button.
slideshow.autoStartfalseStart playing when the lightbox opens.
slideshow.interval4000Milliseconds per slide.
slideshow.pauseOnHoverfalsePause 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 #

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:

js
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',
      ],
    },
  },
};

Because a function cannot be compared, the shared lightbox is rebuilt when you assign a new function in the toolbar config.

Keyboard #

KeyAction
Right and left arrowsnext and prev (swapped in right-to-left pages)
Home and Endfirst and last
+ or = and - or _zoomIn and zoomOut
0zoomReset
Spaceslideshow (play or pause)
ffullscreen
EscClose (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.

js
grid.options = { lightbox: { keyboard: { j: 'next', k: 'prev', ' ': null } } };
grid.options = { lightbox: { keyboard: false } }; // no shortcuts, Esc still closes

Events #

The grid element emits these (all bubble):

Eventdetail
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:

js
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 #

js
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:

html
<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.