DocumentationMigrating from Media Boxes version 3

Migrating from Media Boxes version 3

Move a Media Boxes version 3 jQuery grid to version 4.0. See what changed, how options, markup, callbacks and CSS map across, a before and after example and an FAQ.

Version 4.0 is a rewrite. It has no dependency on jQuery, Isotope, Fancybox or Magnific Popup, and it is not drop-in compatible with version 3. Your version 3 markup, your $('#grid').mediaBoxes({...}) call and your version 3 CSS overrides will not work with version 4.0 as they are. This guide shows how to convert each part.

Who needs this guide #

You need it if you installed Media Boxes version 3 on a site and now want that site to use version 4.0. You also need it if you have version 3 code in a theme or template that you will update later.

You do not need it for a new site. Start from the version 4.0 documentation and demos instead.

Before you update: keep a copy of version 3 #

Envato lets buyers download only the latest version of an item. The download for version 4.0 does not include the jQuery plugin, so before you update, copy the version 3 files you use (the plugin folder, your CSS overrides and your page templates) to a safe place. If you already deployed them on a site, those files keep working as they are.

You do not have to migrate #

Your version 3 sites keep working. Nothing about version 3 changes: the same files, the same jQuery calls. You can stay on version 3 for as long as you want, and move a page only when you want the new features, when you are redesigning it, or when you want to drop jQuery. You can migrate one grid at a time.

What changed at a glance #

AreaVersion 3Version 4.0
How you start it$('#grid').mediaBoxes({...})A <media-boxes> tag in the page. No init call
DependenciesjQuery, Isotope, imagesLoaded, Transit, jQuery Easing, jQuery Visible, Modernizr, Fancybox or Magnific PopupNone
Files to loadAbout 10 scripts and 2 to 4 stylesheetsOne script and one stylesheet
Download sizeAbout 93 kB gzipped of JavaScript (jQuery and Fancybox included)About 34 kB gzipped of JavaScript and 7 kB gzipped of CSS
LayoutsOne (masonry through Isotope)masonry, grid, justified, mosaic
Item class.media-box.mb-item
FiltersCSS class selectors in data-filterTerms in data-category (or any group name)
Filter, search and sort barsMarkup you writeBuilt by the engine from options (or your own controls, linked by data-mb-for)
LightboxFancybox or Magnific Popup (separate libraries)One built-in lightbox with zoom, swipe, thumbnails, slideshow, fullscreen
Overlay effects15 values, driven by jQuery animation10 values, driven by CSS
Responsive rulesresolutions, matched against the window widthbreakpoints, matched against the width of the grid
CallbacksonLayoutFinish, onPopupStart, onPopupCloseDOM events such as mb:layout, mb:open, mb:close
Methods$('#grid').mediaBoxes('insert', ...)grid.addItems(...) on the element
StylingOverride .media-box-* classes, often with !importantCSS custom properties (--mb-*) and mb-* classes, no !important needed
Without JavaScriptBoxes are hiddenItems show as a plain CSS grid
BrowsersIncluded Internet ExplorerCurrent Chrome, Edge, Firefox and Safari 16.4 or newer

Before you start #

Step-by-step migration #

Step 1. Remove jQuery and the old files #

Remove these from the page, if they are only there for Media Boxes:

Keep jQuery if other scripts on your site need it. Version 4.0 does not care whether jQuery is on the page.

Keep Font Awesome only if your own markup still uses its icons (for example <i class="fa fa-plus"> inside an overlay). Version 4.0 does not need it and does not load it.

Step 2. Add the version 4.0 files #

Add one stylesheet and one script:

html
<link rel="stylesheet" href="path/to/media-boxes.css">
<script defer src="path/to/media-boxes.js"></script>

The script defines the <media-boxes> element. You do not call anything to start it. If you use a bundler, import media-boxes.esm.js instead.

The stylesheet is wrapped in a CSS layer named media-boxes. Any CSS you write yourself, outside a layer, wins over it without !important.

Step 3. Convert the markup #

Wrap the grid in a <media-boxes> tag and turn every .media-box into a .mb-item. The tag replaces the <div id="grid">. Keep the id if you want deep links, or if external controls need to find the grid.

A version 3 box:

html
<div class="media-box Nature">
  <div class="media-box-image">
    <div data-width="320" data-height="200" data-thumbnail="thumbs/55.jpg"></div>
    <div class="thumbnail-overlay">
      <i class="fa fa-plus mb-open-popup" data-src="full/55.jpg" data-title="Dolor sit amet"></i>
    </div>
  </div>
  <div class="media-box-content">
    <div class="media-box-title">Dolor sit amet</div>
    <div class="media-box-text">Lorem ipsum dolor sit amet.</div>
  </div>
</div>

The same item in version 4.0:

html
<article class="mb-item" data-category="Nature">
  <a class="mb-media" href="full/55.jpg">
    <img src="thumbs/55.jpg" width="320" height="200" alt="Dolor sit amet" loading="lazy">
  </a>
  <div class="mb-content">
    <h3 class="mb-title">Dolor sit amet</h3>
    <p class="mb-text">Lorem ipsum dolor sit amet.</p>
  </div>
</article>

The rules:

For YouTube, Vimeo, video files, iframes and inline HTML, the lightbox picks the type from the URL. Set data-mb-type on the .mb-media link when you want to force it:

html
<a class="mb-media" href="https://www.youtube.com/watch?v=uf8Fwiy0Bkc">
  <img src="thumbs/video.jpg" width="590" height="332" alt="Launch video">
</a>
<a class="mb-media" href="#more-info" data-mb-type="html">
  <img src="thumbs/info.jpg" width="590" height="332" alt="More information">
</a>

The #more-info target is an element elsewhere on the page. Hide it with the hidden attribute. The lightbox shows a copy of its content.

Filters, search and sort bars #

Delete your version 3 <ul class="media-boxes-filter">, the search box and the sort drop-down. The engine builds them from options (Step 4). If you want to keep your own HTML, give the grid an id and link your controls to it with data-mb-for:

html
<nav>
  <button data-mb-for="portfolio" data-mb-filter="category:*">All</button>
  <button data-mb-for="portfolio" data-mb-filter="category:nature">Nature</button>
  <button data-mb-for="portfolio" data-mb-sort="title">A to Z</button>
  <button data-mb-for="portfolio" data-mb-sort="title:desc">Z to A</button>
  <input type="search" data-mb-for="portfolio" data-mb-search placeholder="Search">
</nav>

The filter value is group:slug. A slug is the lowercase term with spaces turned into hyphens, so "Nature & Outside" becomes nature-outside. Active buttons get the class is-active and aria-pressed="true".

Step 4. Convert the options #

Version 4.0 reads options from four places. Later ones win:

The attributes are layout, columns, min-column-width, gap, aspect-ratio, row-height, skin, enter, theme, load, initial, step, hover-overlay, hover-image, filter, search and lightbox. The filter attribute is a shortcut: filter="category" creates one row of filter buttons for that group.

A version 3 init:

js
$('#grid').mediaBoxes({
  filterContainer: '#filter',
  search: '#search',
  columns: 3,
  boxesToLoadStart: 9,
  boxesToLoad: 9,
  horizontalSpaceBetweenBoxes: 30,
  verticalSpaceBetweenBoxes: 30,
  overlayEffect: 'direction-aware',
  deepLinkingOnFilter: false
});

The same grid in version 4.0:

html
<media-boxes id="grid" columns="3" gap="30" load="button" initial="9" step="9"
             hover-overlay="direction" filter="category" search>
  <script type="application/json" data-mb-options>
    { "deepLink": { "filter": false } }
  </script>
  <!-- items -->
</media-boxes>

Use the option tables below for every other option.

Two defaults differ from version 3 and are worth setting on purpose:

Step 5. Convert callbacks and method calls #

Callbacks become DOM events on the <media-boxes> element, and jQuery method calls become methods on that element:

js
const grid = document.querySelector('#grid');

// version 3: onPopupStart / onPopupClose
grid.addEventListener('mb:open', (e) => console.log('opened', e.detail.item.id));
grid.addEventListener('mb:close', () => console.log('closed'));

// version 3: onLayoutFinish
grid.addEventListener('mb:layout', (e) => console.log(e.detail.height, e.detail.columns));

// version 3: $('#grid').mediaBoxes('insert', $(box), callback)
grid.addItems(newItemElement);

Methods do nothing until the grid is ready. If your script runs early, wait for the mb:ready event. The full table is in "Methods and events" below.

Step 6. Convert your CSS #

Your version 3 overrides targeted .media-box-* and .thumbnail-overlay classes, and often needed !important. In version 4.0 you change the look with CSS custom properties set on the grid, and with the mb-* classes for anything the tokens do not cover.

css
/* version 3 */
.media-box-container { border-radius: 0; box-shadow: none; }
.media-box-title { font-weight: 100; text-align: center; }
.media-boxes-filter > li a.selected { background: #e54e53; color: #fff; }

/* version 4.0 */
#portfolio {
  --mb-radius: 0;
  --mb-shadow: none;
  --mb-shadow-hover: none;
  --mb-title-weight: 300;
  --mb-accent: #e54e53;
  --mb-accent-contrast: #ffffff;
}
#portfolio .mb-title { text-align: center; }

The tokens you will use most:

TokenWhat it controls
--mb-font, --mb-font-size, --mb-title-size, --mb-title-weightType
--mb-text, --mb-text-muted, --mb-surface, --mb-borderText, card background, hairlines
--mb-accent, --mb-accent-contrastActive filter, buttons, focus-adjacent accents
--mb-radius, --mb-shadow, --mb-shadow-hoverShape and depth of cards
--mb-overlay-bg, --mb-overlay-textThe hover overlay on images
--mb-duration-hover, --mb-easeSpeed and easing of hover effects (replaces overlaySpeed and overlayEasing)
--mb-label-transform, --mb-label-trackingCategory labels. Set uppercase and 0.08em for capital letters
--mb-lb-bg, --mb-lb-text, --mb-lb-controlThe lightbox colors

For a dark page use theme="dark" on the grid (or theme="auto" to follow the visitor's system setting). Do not copy version 3 CSS for Fancybox or Magnific Popup. Those libraries are gone, and the version 4.0 lightbox is styled with the --mb-lb-* tokens.

The class mapping is in "Markup mapping" below.

Step 7. Test checklist #

Open the page and check each item:

Full example: the portfolio page #

This converts the version 3 example/portfolio.html page. It has a filter bar, a search box, a 3-column grid with fixed-ratio thumbnails, a "reveal" overlay, and the Magnific Popup lightbox.

version 3 #

html
<link rel="stylesheet" href="plugin/components/Font Awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="plugin/components/Magnific Popup/magnific-popup.css">
<link rel="stylesheet" href="plugin/css/mediaBoxes.css">

<div class="media-boxes-search">
  <span class="media-boxes-icon fa fa-search"></span>
  <input type="text" id="search" placeholder="Search by title">
  <span class="media-boxes-clear fa fa-close"></span>
</div>

<ul class="media-boxes-filter" id="filter">
  <li><a class="selected" href="#" data-filter="*">All</a></li>
  <li><a href="#" data-filter=".Indoors">Indoors</a></li>
  <li><a href="#" data-filter=".Nature, .Outside">Nature and Outside</a></li>
  <li><a href="#" data-filter=".Life">Life</a></li>
</ul>

<div id="grid">
  <div class="media-box Nature">
    <div class="media-box-image" data-overlay-effect="fade">
      <div data-width="320" data-height="200" data-thumbnail="gallery/thumbnails/thumb-55.jpg"></div>
      <div class="thumbnail-overlay">
        <a href="#" class="mb-open-popup btn btn-sm btn-default" data-src="gallery/img-55.jpg" data-title="Dolor sit amet">View Larger</a>
        <a href="#" class="btn btn-sm btn-default">More Details</a>
      </div>
    </div>
    <div class="media-box-content">
      <div class="media-box-categories"><span>Nature</span></div>
      <div class="media-box-title">Dolor sit amet</div>
      <div class="media-box-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
      <div class="media-box-date">December 10, 2013</div>
    </div>
  </div>

  <div class="media-box Indoors">
    <!-- same structure, thumb-14.jpg and img-14.jpg -->
  </div>
  <!-- more boxes: Life, Outside, ... -->
</div>

<script src="plugin/components/jQuery/jquery-3.6.0.min.js"></script>
<script src="plugin/components/Isotope/jquery.isotope.min.js"></script>
<script src="plugin/components/imagesLoaded/jquery.imagesLoaded.min.js"></script>
<script src="plugin/components/Transit/jquery.transit.min.js"></script>
<script src="plugin/components/jQuery Easing/jquery.easing.js"></script>
<script src="plugin/components/jQuery Visible/jquery.visible.min.js"></script>
<script src="plugin/components/Modernizr/modernizr.custom.min.js"></script>
<script src="plugin/components/Magnific Popup/jquery.magnific-popup.min.js"></script>
<script src="plugin/js/jquery.mediaBoxes.dropdown.js"></script>
<script src="plugin/js/jquery.mediaBoxes.js"></script>
<script>
  $('#grid').mediaBoxes({
    filterContainer: '#filter',
    search: '#search',
    overlayEffect: 'reveal-bottom',
    columns: 3,
    boxesToLoadStart: 6,
    boxesToLoad: 6,
    horizontalSpaceBetweenBoxes: 30,
    verticalSpaceBetweenBoxes: 30,
    popup: 'magnificpopup'
  });
</script>

<style>
  .media-box-container { border-radius: 0; box-shadow: none; }
  .media-box-categories span { font-size: 9px; text-transform: uppercase; letter-spacing: 2px; color: #e54e53; }
  .media-box-title { text-align: center; font-size: 20px; font-weight: 100; }
</style>

version 4.0 #

html
<link rel="stylesheet" href="path/to/media-boxes.css">
<script defer src="path/to/media-boxes.js"></script>

<media-boxes id="portfolio" layout="grid" columns="3" gap="30" aspect-ratio="16/10"
             skin="card" hover-overlay="reveal" hover-image="none"
             load="button" initial="6" step="6" search>
  <script type="application/json" data-mb-options>
    { "filters": [{ "group": "category", "ui": "pills", "multiple": true }] }
  </script>

  <article class="mb-item" data-category="Nature" data-date="2013-12-10">
    <a class="mb-media" href="gallery/img-55.jpg">
      <img src="gallery/thumbnails/thumb-55.jpg" width="320" height="200" alt="Dolor sit amet" loading="lazy">
      <span class="mb-overlay"><span class="mb-overlay-label">View larger</span></span>
    </a>
    <div class="mb-content">
      <p class="mb-cats"><span>Nature</span></p>
      <h3 class="mb-title"><a href="project-55.html">Dolor sit amet</a></h3>
      <p class="mb-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
      <p class="mb-meta"><time class="mb-date" datetime="2013-12-10">December 10, 2013</time></p>
    </div>
  </article>

  <article class="mb-item" data-category="Indoors" data-date="2013-12-10">
    <!-- same structure, thumb-14.jpg and img-14.jpg -->
  </article>
  <!-- more items: Life, Outside, ... -->
</media-boxes>

<style>
  #portfolio {
    --mb-radius: 0;
    --mb-shadow: none;
    --mb-shadow-hover: none;
    --mb-title-size: 1.25rem;
    --mb-title-weight: 300;
    --mb-accent: #e54e53;
    --mb-label-transform: uppercase;
    --mb-label-tracking: 0.12em;
  }
  #portfolio .mb-cats { color: #e54e53; }
  #portfolio .mb-title { text-align: center; }
</style>

What changed and why:

Option mapping #

Every option in the version 3 source (jquery.mediaBoxes.js, the DEFAULTS object) is listed here. The version 3 documentation lists fewer. Where they differ, this guide follows the source, because that is what the code actually did.

Loading #

Version 3 option (default)Version 4.0Notes
boxesToLoadStart (8)load.initial or attribute initialRenamed. Version 4.0 default is 12
boxesToLoad (4)load.step or attribute stepRenamed. Version 4.0 default is 8
lazyLoad (true)load.modetrue becomes 'scroll' (loads as you reach the end). false becomes 'button'. Also available: 'pages' and 'all'
minBoxesPerFilter (0)Not neededVersion 4.0 filters across all items and then applies initial and step to the filtered list, so a filter never shows an empty or short page while more items exist. Remove the option
LoadingWord ('Loading...')i18n.loadingThe key exists, but items already in the page load instantly, so it is rarely visible
loadMoreWord ('Load More')i18n.loadMoreThe button also shows how many items are left
noMoreEntriesWord ('No More Entries')NoneThe button disappears when there is nothing left to load

Layout and spacing #

Version 3 option (default)Version 4.0Notes
horizontalSpaceBetweenBoxes (15) and verticalSpaceBetweenBoxes (15)gapOne option. A number, or [rowGap, columnGap]. The vertical value comes first: Version 3 horizontal: 30, vertical: 10 becomes gap: [10, 30]. Negative values become 0
columns (4)columnsSame. Version 4.0 also accepts 'auto'
columnWidth ('auto')columns: 'auto' and minColumnWidthA fixed pixel column width becomes a minimum width. The engine fits as many columns as it can
resolutions (3 entries)breakpointsSee below
percentage (false)NoneColumn widths are always calculated for you

resolutions and breakpoints differ in three ways:

js
// version 3
resolutions: [
  { maxWidth: 960, columnWidth: 'auto', columns: 4 },
  { maxWidth: 888, columnWidth: 'auto', columns: 2 },
  { maxWidth: 450, columnWidth: 'auto', columns: 1, horizontalSpaceBetweenBoxes: 10, verticalSpaceBetweenBoxes: 10 }
]

// version 4.0 (the order does not matter, the engine sorts them)
breakpoints: [
  { maxWidth: 960, columns: 4 },
  { maxWidth: 888, columns: 2 },
  { maxWidth: 450, columns: 1, gap: 10 }
]

Filter, search and sort #

Version 3 option (default)Version 4.0Notes
filterContainer ('#filter')filtersAn array of groups: [{ group: 'category', ui: 'pills', multiple: false, counts: false, all: 'All', label: '' }]. The ui is 'pills', 'tabs' or 'select'. Items carry data-<group>. Or use data-mb-for controls
multipleFilterLogic ('AND')filterLogicValue must be lowercase: 'and' or 'or'. An uppercase 'OR' is ignored and the default 'and' is used
search ('')searchtrue, or { placeholder, fields, ui }. For your own input, use <input data-mb-search data-mb-for="id">
searchTarget ('.media-box-title')search.fieldsField names, not selectors. Default ['title', 'text']. You can add a filter group name or any data-* name
sortContainer ('')sort{ options: [{ key: 'title', label: 'Title' }], default: 'index', order: 'asc' }
getSortData (title, text)sort.options and data-* attributesKeys index, title, text, date and random are built in. For anything else, put the value in a data-* attribute, such as data-year="2013". Numbers are detected, so the version 3 parseInt suffix is not needed

Example: a version 3 grid sorted by title and year.

js
// version 3
getSortData: { title: '.media-box-title', year: '.media-box-year parseInt' },
sortContainer: '#sort'
html
<!-- version 4.0 -->
<article class="mb-item" data-year="2013"> ... </article>

<script type="application/json" data-mb-options>
  { "sort": { "options": [
      { "key": "index", "label": "Original order" },
      { "key": "title", "label": "Title" },
      { "key": "year", "label": "Year" }
  ] } }
</script>

Deep linking #

Version 3 option (default)Version 4.0Notes
deepLinkingOnFilter (true)deepLink.filterThe grid needs an id
deepLinkingOnSearch (false)deepLink.search
deepLinkingOnPopup (true)deepLink.lightbox

The URL format changed from #(grid|filter)=.category1; to #grid?category=nature&q=lake&item=p1. Bookmarks made with version 3 do not carry over. You can turn it all off with "deepLink": false.

Thumbnails and loading look #

Version 3 option (default)Version 4.0Notes
waitUntilThumbWithRatioLoads (true)NoneVersion 4.0 reserves the space from the image's width and height, then fades the image in when it has loaded
waitForAllThumbsNoMatterWhat (false)NoneThe layout never waits for images when width and height are set. If they are missing, the engine measures each image when it loads
noEmptySpaceOnThumbWithRatio (true)NoneAlways on: images fill their frame (object-fit: cover)

Overlay and hover #

Version 3 option (default)Version 4.0Notes
thumbnailOverlay (true)hover.overlayfalse becomes 'none'
overlayEffect ('fade')hover.overlay or attribute hover-overlaySee the value table below
overlaySpeed (200)--mb-duration-hoverA CSS token in milliseconds. Default 280ms. Set it on the grid
overlayEasing ('default')--mb-easeA CSS token with one easing curve for everything. The 20-odd named easings are gone
animation_on_thumbnail_overlay_hoverNoneUse CSS (see "Removed features")

Overlay effect values:

Version 3 overlayEffectVersion 4.0 hover.overlayNotes
fadefade
push-up, push-up-100%slide-upThe overlay slides over the image. In version 3 it pushed the image up with it
push-down, push-down-100%slide-downSame note
reveal-top, reveal-top-100%, reveal-bottom, reveal-bottom-100%revealA band rises from the bottom while the image drifts up. There is no top variant
direction-aware, direction-aware-fadedirectionEnters from the side the pointer came from
direction-rightslide-leftThe overlay enters from the right
direction-leftslide-rightThe overlay enters from the left
direction-topslide-downThe overlay enters from the top
direction-bottomslide-upThe overlay enters from the bottom

Version 4.0 adds zoom and blur, plus an image effect (hover.image: zoom, zoom-out, grayscale, color, blur, tilt or none). On touch screens the hover overlay is not drawn: a tap opens the item.

Check each converted effect by eye. The names differ and the motion is similar, not identical.

Version 3 option (default)Version 4.0Notes
popup ('fancybox')lightbox.enabled or attribute lightboxOne built-in lightbox. 'fancybox' and 'magnificpopup' both become the default. 'none' becomes lightbox="false"
considerFilteringInPopup (true)lightbox.scopetrue becomes 'filtered'. false becomes 'all'
showOnlyVisibleBoxesInPopup (false)NoneVersion 4.0 'filtered' scope includes items not loaded yet. The version 3 documentation calls this option showOnlyLoadedBoxesInPopup, a name that never existed in the code
magnificpopup (object)See the next table
fancybox (object)See the table after it
facebook, twitter, googleplus, pinterest (hidden, Magnific only)lightbox.shareVersion 4.0 has one share button: the system share sheet, or copy link

Fancybox sub-options #

Version 3 fancybox. option (default)Version 4.0Notes
loop (false)lightbox.loopVersion 4.0 default is true
margin ([44, 0])NoneThe lightbox fits the image in the stage by itself
keyboard (true)lightbox.keyboardtrue, false, or an object that maps keys to actions
arrows (true)NoneArrows show on devices with a pointer and hide on touch. To hide them everywhere: .mb-lightbox .mb-lb-arrow { display: none; }
infobar (false)lightbox.counterVersion 4.0 default is true
toolbar (true)lightbox.toolbarnull is the default bar. Or { left: [...], right: [...] }
buttons (slideShow, fullScreen, thumbs, close)lightbox.toolbar.rightKeys: 'zoom', 'slideshow', 'fullscreen', 'download', 'share', 'thumbs', 'close'. You can add your own buttons
idleTime (seconds)lightbox.idleMilliseconds, or false. It hides the controls only during a slideshow or in fullscreen
protect (false)None
animationEffect ('zoom')lightbox.openAnimation'zoom' (from the thumbnail) or 'fade'
animationDuration (330)NoneMotion uses a spring. Set lightbox.motion to 'ease' for plain CSS easing
transitionEffect ('fade')lightbox.transition'slide' (default) or 'fade'. The other effects are gone
transitionDuration (330)None
slideShow ({ autoStart, speed })lightbox.slideshow{ enabled, autoStart, interval }. speed is now interval, in milliseconds
fullScreen ({ autoStart })lightbox.fullscreenA boolean. No auto start
thumbs ({ autoStart, hideOnClose })lightbox.thumbnailsA boolean. The strip is shown when it is on
touchNoneSwipe, pinch, double tap and drag-to-close are always on. Turn drag-to-close off with swipeToClose: false
compensateScrollbarNonePage scroll is locked without a layout shift
share (not documented)lightbox.share

Magnific Popup sub-options #

Version 3 magnificpopup. option (default)Version 4.0Notes
gallery (true)NoneThe lightbox always lets you move between items
alignTop (false)None
preload ([0, 2])lightbox.preloadOne number: slides loaded on each side of the current one (0 to 5, default 1)

Callbacks #

Version 3 optionVersion 4.0 eventNotes
onLayoutFinishmb:layoute.detail is { height, columns }. It fires on every layout, not only after inserts
onPopupStartmb:opene.detail is { item, index }
onPopupClosemb:close

Totals #

The version 3 source has 42 top-level options. In version 4.0, 28 have an equivalent (some renamed, some replaced by a different approach such as an attribute, a CSS token or an event), and 14 are removed because version 4.0 makes them unnecessary or does not offer them. Of the 22 sub-options of fancybox and magnificpopup, 13 have an equivalent.

Markup mapping #

Version 3Version 4.0Notes
<div id="grid"><media-boxes id="grid">
.media-box.mb-itemDirect child of <media-boxes>
Category classes on the box (class="media-box Nature")data-category="Nature"Comma-separated for several. Other groups use data-<group>
data-columns="2"data-cols="2" (and data-rows)Spans columns in masonry, grid and mosaic layouts. Capped at the column count
data-extra-height="15"NoneHeights come from the content. Use the grid layout for equal rows
.media-box-image.mb-mediaAn <a href="large-image"> to open the lightbox
div[data-thumbnail]<img src> inside .mb-media
data-width, data-height on the thumbnailwidth, height on the <img>Real pixel size of the file. For a fixed crop, use layout="grid" and aspect-ratio
data-title, data-alt on the thumbnailalt on the <img>, and the text of .mb-title
data-thumbnail="none"Omit .mb-mediaAn item with only content
data-overlay-effect on .media-box-imageNoneOne effect per grid
.thumbnail-overlay.mb-overlayOptional. Added automatically for lightbox items
.overlay-always-visibleskin="overlay"The skin keeps the title on the image all the time
.overlay-text-left, .overlay-text-rightCSS: text-align
.mb-open-popup with data-src<a class="mb-media" href>The whole media area is the trigger
Second and later .mb-open-popup in one box<li><a href> inside <ul class="mb-gallery" hidden>See "More than one popup trigger in a box"
data-type="image"Automatic
data-type="iframe" (YouTube, Vimeo, other)Automatic for YouTube and Vimeo. data-mb-type="iframe" for othersdata-mb-type values: image, video, youtube, vimeo, iframe, html, link
data-type="inline" with data-src="#id"data-mb-type="html" with href="#id"Hide the target with the hidden attribute. Its content is copied into the lightbox
data-type="ajax"NoneSee "Removed features"
data-title on the popup triggerThe .mb-title text, or data-mb-caption for a longer caption
data-thumb on the popup triggerAutomaticTaken from the <img>
.iframe-on-griddata-mb-play="inline" or videoPlay: 'inline'The player replaces the thumbnail in place. See "Videos playing inside the grid"
.media-box-content.mb-content
.media-box-title, .media-box-text.mb-title, .mb-text
.media-box-date.mb-date inside .mb-meta, with data-date="2013-12-10" on the item for sorting
.media-box-categories.mb-catsWrite it yourself in markup, or let showTerms do it for items built from data
.media-box-more, .media-box-price, .media-box-author and other version 3 style helpers.mb-price, .mb-author, .mb-badge exist. Others become your own classesThe version 3 helper classes only carried CSS
<ul class="media-boxes-filter" id="filter"> with data-filterfilters option, or data-mb-filter="group:slug" controls
<select id="filter"> with data-filter optionsfilters: [{ group, ui: 'select' }]
.media-boxes-drop-down filtersui: 'select'
Checkbox filters (.media-boxes-checkboxes)multiple: true pills, or your own checkboxes calling grid.filter()See the FAQ
data-id on a filter containerOne entry per group in filters
data-visible-only-ifNone
.media-boxes-search with #searchsearch: true, or <input data-mb-search data-mb-for>
.media-boxes-sort, .media-boxes-drop-down with data-sort-bysort option, or data-mb-sort="key:order" controls
data-sort-ascending, data-sort-togglesort.order. The built-in order button toggles
.media-boxes-load-more (button, created by the plugin).mb-load-more (created by the engine)
.media-box-loaded, .media-box-hidden, .hidden-media-boxes-by-filter.is-loaded (on .mb-media), .is-hidden, .is-entering, .is-leavingState classes
.media-box-container (inner wrapper).mb-item

Methods and events #

Grab the element and call the method on it. There is no jQuery wrapper.

js
const grid = document.querySelector('#grid');
Version 3 callVersion 4.0Notes
$('#grid').mediaBoxes(options)Attributes, a JSON block, or grid.options = {...}Setting options merges into the current ones and re-renders
$('#grid').mediaBoxes('destroy')grid.destroy()Restores the original children and removes listeners. The element is finished afterwards. To start again, insert a new <media-boxes>
$('#grid').mediaBoxes('insert', content, cb)grid.addItems(items, { position: 'end' })Takes elements or plain data objects. Also position: 'start'. There is no callback: listen for mb:layout. New items follow the normal loading rules (initial, step)
$('#grid').mediaBoxes('insert_in_flow', content, cb)grid.addItems(...)Same call. Version 4.0 always adds items into the loading flow
$('#grid').mediaBoxes('refresh')grid.layout()Lays out again. Use grid.refresh() to also re-read the DOM and options
$('#grid').mediaBoxes('resize')grid.refresh()The grid already re-lays out when its width changes

New in version 4.0: filter(group, value), search(text), sort(key, order), loadMore(), goToPage(n), removeItems(idsOrElements), openLightbox(idOrIndex), closeLightbox(), and the read-only items, visibleItems and query.

insert took an HTML string through jQuery. addItems takes elements, so parse your string first:

js
const tpl = document.createElement('template');
tpl.innerHTML = htmlString.trim();
grid.addItems([...tpl.content.children]);

Or build items from data and let the engine render them:

js
grid.addItems([{
  id: 'p101',
  title: 'New project',
  terms: { category: ['Nature'] },
  thumb: { src: 'thumbs/101.jpg', width: 640, height: 400, alt: 'New project' },
  media: { type: 'image', src: 'full/101.jpg' }
}]);

Events fire on the <media-boxes> element and bubble. The ones you are most likely to use:

Evente.detailWhen
mb:readynoneThe grid has started
mb:layout{ height, columns }After every layout
mb:filter{ query, count }A filter, search or sort changed
mb:load{ added, visible, total }More items were revealed
mb:open{ item, index }The lightbox opened
mb:change{ item, index }The lightbox moved to another slide
mb:closenoneThe lightbox closed

The lightbox also fires mb:lightbox-ready, mb:lightbox-slide-loaded, mb:lightbox-slide-error, mb:lightbox-zoom and mb:lightbox-before-close (cancelable).

Removed features and workarounds #

Fancybox and Magnific Popup are gone #

There is one lightbox, built in. Its options are listed above. If you passed unusual Fancybox options, check the table: the ones without an equivalent (margin, protect, durations, other transition effects) are not available.

Ajax popup content #

The ajax type loaded a same-origin HTML file into the popup. Options:

More than one popup trigger in a box #

Version 3 allowed several .mb-open-popup elements in one box, each with its own image. In version 4.0 the first one is the media link and the others go in a hidden list inside the item.

Before (version 3):

html
<div class="media-box Projects">
  <div class="media-box-image" data-thumbnail="thumbs/55.jpg">
    <div class="thumbnail-overlay">
      <i class="fa fa-plus mb-open-popup" data-src="full/55.jpg" data-title="Front"></i>
      <i class="fa fa-plus mb-open-popup" data-src="full/56.jpg" data-title="Back"></i>
      <i class="fa fa-plus mb-open-popup" data-src="full/57.jpg" data-title="Side"></i>
    </div>
  </div>
</div>

After (version 4.0):

html
<article class="mb-item" data-id="p55" data-category="Projects">
  <a class="mb-media" href="full/55.jpg"><img src="thumbs/55.jpg" width="720" height="480" alt="Front"></a>
  <ul class="mb-gallery" hidden>
    <li><a href="full/56.jpg" title="Back">Back</a></li>
    <li><a href="full/57.jpg" title="Side">Side</a></li>
  </ul>
</article>

The tile shows a chip with the number of slides, and the lightbox flips through the three of them. Set lightbox: { itemGallery: 'isolated' } to keep a visitor inside one project's photos. Details in Lightbox.

Videos playing inside the grid #

.iframe-on-grid replaced the thumbnail with a player. In version 4.0 set videoPlay: 'inline' on the grid, or data-mb-play="inline" on single items.

Before (version 3):

html
<div class="media-box-image">
  <div data-width="590" data-height="332" data-thumbnail="thumbs/film.jpg"></div>
  <div class="thumbnail-overlay iframe-on-grid" data-type="iframe" data-src="https://www.youtube.com/watch?v=aqz-KE-bpKQ">
    <span class="fa fa-play media-box-play-button"></span>
  </div>
</div>

After (version 4.0):

html
<article class="mb-item" data-mb-play="inline" data-duration="4:12">
  <a class="mb-media" href="https://www.youtube.com/watch?v=aqz-KE-bpKQ"><img src="thumbs/film.jpg" width="720" height="405" alt="Film"></a>
</article>

The click starts the video in the same box, with a stop button. Version 3 also used iframe-on-grid for other embeds such as SoundCloud: use data-mb-type="iframe" with data-mb-play="inline" for those. Without the attribute, video items open in the lightbox and the grid shows a play icon (and a duration chip with data-duration); videoBadge: false turns the icon off. See Skins and captions.

Different overlay effect per box #

data-overlay-effect is gone. Use one effect per grid. If you need two, use two <media-boxes> elements.

Animating icons inside the overlay #

animation_on_thumbnail_overlay_hover moved icons and text in when the overlay appeared. Do it in CSS:

css
#portfolio .mb-overlay .mb-overlay-icon {
  transition: translate var(--mb-duration-hover) var(--mb-ease);
  translate: 0 30px;
}
#portfolio .mb-item:hover .mb-overlay .mb-overlay-icon { translate: 0 0; }

A link cannot sit inside another link. Because .mb-media is the link that opens the lightbox, keep the overlay to text and icons. Move other links to .mb-content, for example on the title.

Always-visible overlay text #

Use skin="overlay" (content on a gradient over the image, always visible) or skin="hover" (content revealed on hover, always visible on touch screens). Other skins: card, plain, caption, image.

Filtering with CSS selectors #

Version 3 data-filter accepted any selector: .a, .b, .a.b, :not(.c). Version 4.0 filters by terms:

Checkbox, radio and show-only-if filters #

Version 4.0 builds filter buttons, tabs and selects. It does not build checkboxes or radios, and it has no data-visible-only-if. For a checkbox group, build your own inputs and call the API:

js
document.querySelectorAll('.my-filters input[type=checkbox]').forEach((box) => {
  box.addEventListener('change', () => {
    const picked = [...document.querySelectorAll('.my-filters input:checked')].map((i) => i.value);
    grid.filter('category', picked); // an empty array shows everything
  });
});

Terms inside one group combine with OR. Several groups combine with filterLogic.

Sort direction per option #

Version 3 could give each sort option its own direction and toggle. Version 4.0 has one order button in the built-in bar. For per-option directions, use your own controls: data-mb-sort="title" and data-mb-sort="title:desc".

Negative spacing #

The "Circular Fun" example used negative gaps to overlap thumbnails. gap cannot be negative in version 4.0.

Social sharing buttons #

The Facebook, Twitter, Google+ and Pinterest buttons are removed. Set lightbox.share: true for a share button that uses the system share sheet and falls back to copying the link.

Icons #

Version 3 shipped with Font Awesome. Version 4.0 uses its own inline icons and does not load an icon font. In your own overlay markup, use inline SVG, or keep Font Awesome on the page yourself.

Old internals #

Everything that talked to the jQuery plugin is gone: $('#grid').data('settings'), the isotopeMB plugin, and the fancyboxMB object. If your theme called any of them, replace them with the methods and events above.

Browser support #

Version 3 ran in old browsers, including Internet Explorer. Version 4.0 targets the last two versions of Chrome, Edge, Firefox and Safari (Safari 16.4 or newer). It uses custom elements, ES modules, CSS layers and modern CSS. There is no polyfill and no compatibility build, so Internet Explorer and older browsers will not run it. Without JavaScript, the items still show as a plain CSS grid.

If you must support an older browser, keep that page on version 3 (use the copy of the files you saved).

FAQ #

Do I have to migrate? #

No. Version 3 keeps working on the sites where it is installed, and you can stay on it as long as you want. Keep a copy of your version 3 files before updating, because the new download does not include them.

Can I migrate one grid at a time? #

Yes. The version 4.0 classes all start with mb-, so they do not collide with version 3's .media-box-* classes. Both versions can be on one page. If both use deep links, turn them off in one of them, because both write to the URL hash.

Do I still need jQuery? #

Not for Media Boxes. Leave it on the page if other code uses it.

My version 3 init call does nothing now. Why? #

$.fn.mediaBoxes no longer exists, because the version 3 script is not loaded. Remove the call and configure the <media-boxes> element instead.

Is there a script that converts version 3 markup for me? #

Not at the moment. The conversion is mechanical, so for a large site use search and replace on the repeated parts of your boxes.

Why are my images squashed or the wrong shape? #

In version 3, data-width and data-height set the crop box and the image was fitted to it. In version 4.0, width and height on the <img> should be the file's real size, and the layout follows it. To keep a fixed crop, use layout="grid" with aspect-ratio="16/10" (or your ratio).

My categories do not show up as filters #

Check three things. The grid needs a filters option (or filter="category"). Every item needs data-category (or the group name you chose). The term text is what shows on the button: data-category="Nature" shows "Nature".

How do I show counts on the filter buttons? #

Set "counts": true on the filter: { "group": "category", "counts": true }.

My filter button text is different from version 3 #

The button label is the term as you wrote it in data-category. To rename the "All" button, set "all": "Everything" on the filter, or i18n.all.

Where are my Load More text options? #

In i18n. For example: "i18n": { "loadMore": "Show more" }. The same object holds every label the engine shows, including the lightbox buttons, so it is also how you translate the grid.

Can I still use right-to-left languages? #

Yes. Version 4.0 supports RTL layouts.

How do I get the old look? #

Set skin and the tokens (see Step 6). Start with hover-image="none" and lightbox.loop: false, and match colors with --mb-accent, --mb-radius and --mb-shadow. The look will not be pixel-identical: Version 4.0 is a new design, not a port.

The hash format changed from #(grid|filter)=.nature; to #grid?category=nature. Old links open the page but do not apply the filter. Add redirects only if the old URLs are published somewhere important.