API and events
Control a grid from JavaScript. Methods to filter, search, sort, load, add and remove items and open the lightbox, plus every event with its detail payload.
Each <media-boxes> element is a normal DOM element with methods, properties and events. Get a reference with document.getElementById('work') or document.querySelector('media-boxes') and call it. The API demo has a button for every method and a live event log.
Waiting for the grid #
function whenReady(grid) {
return grid.hasAttribute('data-ready')
? Promise.resolve(grid)
: new Promise((resolve) => grid.addEventListener('mb:ready', () => resolve(grid), { once: true }));
}
const grid = await whenReady(document.getElementById('work'));
grid.filter('category', 'nature');Properties #
| Property | Type | Description |
|---|---|---|
options | object | Getter: the fully resolved options. Setter: merges an object into the options and re-renders. |
items | MBItem[] | Every item, in original order, loaded or not. |
visibleItems | MBItem[] | The items currently shown (after filter, search, sort and loading). |
query | object | A copy of the current query: { filters: { group: [slugs] }, search, sort: { key, order } }. |
An item (MBItem) is a plain object:
| Field | Description |
|---|---|
id | data-id, or mb-<index>. |
el | The .mb-item element. |
index | Position in the original order. |
title, text | The title and description text. |
date | Timestamp in milliseconds, or null. |
terms | Slugs per group, for example { category: ['nature'] }. |
labels | Slug to display label. |
data | Every other data-* attribute, with numbers parsed. |
ratio | Thumbnail width divided by height, or null if not known yet. |
span | { cols, rows }. |
media | { type, src, width?, height?, thumb?, alt?, title?, caption?, poster?, srcset?, sizes? }. |
Methods #
| Method | Description |
|---|---|
filter(group, value) | Select terms of a group. value is a slug or label, an array of them, or '*' to clear the group. |
search(text) | Set the search text. An empty string clears it. |
sort(key, order = 'asc') | Sort by 'index', 'title', 'text', 'date', 'random' or a data name. order is 'asc' or 'desc'. |
loadMore() | Show the next step of items (button and scroll modes). |
goToPage(n) | Go to a page (pages mode). |
addItems(input, { position }) | Add items. input is one or many .mb-item elements or item data objects. position is 'end' (default) or 'start'. Returns the new MBItem[]. |
removeItems(idsOrElements) | Remove items by id, element or MBItem. Returns how many were removed. |
refresh() | Re-read the options and the DOM, picking up .mb-item elements you added by hand and dropping removed ones. |
layout() | Lay the items out again, for example after the container changed size in a way the engine cannot see. |
openLightbox(idOrIndex) | Open the lightbox on an item id (string) or a position (number) among the openable items in scope. |
closeLightbox() | Close it. A mb:lightbox-before-close handler can still prevent this. |
getSlide() | The slide the lightbox is showing for this grid: { id, type, src, title, caption, item, ... } where item is the MBItem. null when the lightbox is closed or is showing another grid. |
getZoom() | The zoom scale of the open slide, where 1 is fit to screen. Returns 1 when the lightbox is closed or is showing another grid. |
destroy() | Restore your original items, remove every listener and clear what the engine added. The element cannot be started again: create a new <media-boxes> if you need one. |
const grid = document.getElementById('work');
grid.addItems([
{
id: 'new1', title: 'Fresh print', terms: { category: ['Nature'] },
thumb: { src: 'images/new1-600.jpg', width: 600, height: 400, alt: 'A fresh print' },
media: { type: 'image', src: 'images/new1-1600.jpg', width: 1600, height: 1067 },
},
], { position: 'start' });
grid.removeItems(['old1', 'old2']);
grid.sort('date', 'desc');
grid.options = { columns: 5, skin: 'overlay' };New items are added to the end of the item list, then the grid re-renders with the entry animation. When the grid loads in parts, an added item may stay hidden until it is loaded.
Events #
All events are CustomEvents that bubble, so you can listen on the grid or on document. The payload is in event.detail.
| Event | detail | When |
|---|---|---|
mb:ready | {} | The grid has been built and laid out. |
mb:layout | { height, columns } | After each layout: the grid height in pixels and the number of columns now in use. |
mb:filter | { query, count } | After a filter, search or sort change. count is the number of items that match. |
mb:load | { added, visible, total } | After loadMore() or goToPage(): items just shown, items shown now, items matching in total. |
mb:open | { item, index } | The lightbox starts to open. |
mb:lightbox-ready | { item, index } | The open animation has settled. |
mb:change | { item, index } | The lightbox moved to another slide. |
mb:lightbox-slide-loaded | { item, index } | A slide, also a preloaded neighbour, finished loading. |
mb:lightbox-slide-error | { item, index } | A slide could not be loaded. |
mb:lightbox-zoom | { item, index, scale } | The zoom of the current slide changed. 1 means fitted. |
mb:lightbox-before-close | { item, index } | The lightbox is about to close. Cancelable: event.preventDefault() keeps it open. |
mb:close | {} | The lightbox closed. |
mb:video-play | { item } | A video started playing inside the grid (inline play). |
mb:video-stop | { item } | An inline video was stopped: by its stop button, because another one started, the item was filtered out, the lightbox opened or the grid was destroyed. |
item is the grid's MBItem. index is the position among the slides the lightbox is flipping through. When items have a gallery (see Lightbox), mb:open, mb:change and the lightbox events also carry slide, the 1-based position inside the item.
grid.addEventListener('mb:filter', (e) => {
document.querySelector('#count').textContent = `${e.detail.count} results`;
});
grid.addEventListener('mb:change', ({ detail }) => {
console.log('now showing', detail.item.title, `(${detail.index + 1})`);
window.gtag?.('event', 'view_photo', { id: detail.item.id });
});
grid.addEventListener('mb:lightbox-before-close', (e) => {
if (formIsDirty) e.preventDefault();
});The global object #
With the classic script, window.MediaBoxes has:
| Export | Description |
|---|---|
MediaBoxesElement | The class behind <media-boxes>. |
DEFAULTS | The default options. |
createLightbox(options) | A standalone lightbox. See Lightbox. |
renderItem(data, options) | Builds an .mb-item element from item data, using textContent only. |
version | The version string. |
With the ES module build the same names are named exports.
const el = MediaBoxes.renderItem({ title: 'Test', thumb: { src: 'a.jpg', width: 4, height: 3 } });
document.querySelector('media-boxes').addItems(el);