DocumentationFiltering and search

Filtering and search

Add filter pills, tabs or selects, several filter groups with AND or OR logic, search, sorting and shareable deep links. Includes outside controls and the API.

Filtering, search and sorting all work on the same set of items, and they combine: an item is shown when it passes every filter, matches the search text, and the result is then sorted. The toolbar is built only if you turn at least one of them on.

Filter groups #

A filter group is a kind of tag, such as category. Items declare their terms in a data-<group> attribute, with several terms separated by commas:

html
<media-boxes id="work" layout="masonry" columns="3" filter="category">
  <article class="mb-item" data-category="Nature, Outside"> ... </article>
  <article class="mb-item" data-category="Architecture"> ... </article>
  <article class="mb-item" data-category="Nature"> ... </article>
</media-boxes>

The filter="category" attribute is a shorthand for one group of pills. The engine collects the terms in the order it first sees them and builds one button per term, plus an All button. Terms are matched by a slug: lowercase, accents removed, runs of other characters turned into -. So Food & Drink is food-drink.

For more control, set filters to an array of groups (in JSON or JavaScript):

js
grid.options = {
  filters: [
    { group: 'category', label: 'Category', ui: 'pills', counts: true },
    { group: 'tone', label: 'Tone', ui: 'select', all: 'Any tone' },
  ],
};
KeyDefaultMeaning
grouprequiredThe group name, which is also the data-<group> attribute on items.
labelnoneA visible label when there are several groups, and the accessible name of the group. Without it the group name with a capital letter is used for the accessible name.
ui'pills''pills' for buttons, 'tabs' for the same buttons styled as underlined tabs, 'select' for a drop-down.
multiplefalseAllow several terms of this group at once. Terms in one group always combine with OR.
all'All'The text of the button that clears the group. It defaults to i18n.all.
countsfalseShow how many items each term would give. Counts respect the other groups and the search text.

A plain string is also accepted: filters: ['category', 'tone'], and the attribute takes a list too: filter="category,tone".

With a single selection the pills behave like radio buttons: clicking the active pill does nothing, and All clears the group. With multiple: true each click toggles a term.

Several groups, AND and OR #

When there is more than one group the toolbar lays them out side by side, separated by a hairline, and stacks them when the grid is 720px wide or less. filterLogic decides how groups combine:

ValueResult
'and' (default)An item must match every group that has a selection.
'or'An item must match at least one group that has a selection.

See the multiple filters demo, which has two groups and a switch between AND and OR.

html
<media-boxes search> ... </media-boxes>
js
grid.options = {
  search: { placeholder: 'Search the work', fields: ['title', 'text', 'category'] },
};

Search without the box #

Set ui: false to keep search active without drawing the box. You can then use your own input, linked by data-mb-for, or call the API:

html
<input type="search" data-mb-for="work" data-mb-search placeholder="Find a project">
<media-boxes id="work" columns="3">
  <script type="application/json" data-mb-options>{ "search": { "ui": false } }</script>
  <!-- items -->
</media-boxes>
js
document.getElementById('work').search('lake');

If you also have no filters and no sort, no toolbar is created at all.

Sorting #

Sorting is off by default. Turn it on with a list of keys:

js
grid.options = {
  sort: {
    options: [
      { key: 'index', label: 'Default' },
      { key: 'title', label: 'Title' },
      { key: 'date', label: 'Newest' },
      { key: 'price', label: 'Price' },
    ],
    default: 'index',
    order: 'asc',
  },
};

The toolbar then shows a drop-down and a button that flips the order. options entries can also be plain strings, where the key is used as the label.

KeySorts by
indexThe original order in the page.
titleThe title, with numbers compared as numbers (Photo 2 before Photo 10).
textThe description text.
datedata-date (an ISO date).
randomA random order that stays the same while you filter, and changes when you pick it again.
any other nameThe data-<name> attribute of the item. Numbers are sorted as numbers, anything else as text.

Items without a value are always placed last, in both directions, and ties keep their original order.

Filtering from outside the grid #

Any button or input in the page can drive a grid, as long as it names the grid's id in data-mb-for:

html
<button type="button" data-mb-for="work" data-mb-filter="category:nature">Nature</button>
<button type="button" data-mb-for="work" data-mb-filter="category:architecture">Architecture</button>
<button type="button" data-mb-for="work" data-mb-filter="category">Show all</button>
<button type="button" data-mb-for="work" data-mb-sort="title">A to Z</button>
<button type="button" data-mb-for="work" data-mb-sort="title:desc">Z to A</button>
<input type="search" data-mb-for="work" data-mb-search placeholder="Search">

From JavaScript #

js
const grid = document.getElementById('work');

grid.filter('category', 'nature');          // one term
grid.filter('category', ['nature', 'travel']); // several, for a multiple group
grid.filter('category', '*');               // clear the group
grid.search('lake');
grid.sort('title', 'desc');

grid.addEventListener('mb:filter', (e) => {
  console.log(e.detail.count, 'items match', e.detail.query);
});

filter accepts slugs or the labels as written ('Food & Drink' is turned into food-drink). Every change fires mb:filter. See API and events.

When the element has an id, its state can live in the address bar, so a filtered view can be copied, bookmarked and reopened:

page.html#work?category=nature,outside&q=lake&sort=title:desc&item=p1
PartMeaning
workThe grid id.
category=nature,outsideThe selected terms of a filter group. Each group gets its own parameter.
q=lakeThe search text.
sort=title:descThe sort key and order. Left out when it equals the default.
item=p1The open lightbox slide, by item id.

Several grids on one page share the hash, separated by |. The state is written with replaceState, so it does not fill the back-button history.

deepLink chooses what is stored:

js
grid.options = { deepLink: { filter: true, search: false, lightbox: true } }; // the default
grid.options = { deepLink: false };                                           // switch it all off

Search is off by default because search text changes with every key press. Turn it on with deepLink: { search: true }. Give items a stable id (data-id) so that item= links keep working when you reorder them. Try it in the deep links demo.

Announcements #

After each change the grid updates a hidden live region with the text from i18n.showing, for example "Showing 12 of 40", or i18n.noResults when nothing matches. The empty state is also drawn on screen.