Filter
Magnet uses filtering to show or hide items with the filter
option. Items matching a filter will be shown, otherwise will be hidden.
Filter by category:
HTML
Items are filtered using selectors or functions. Using selectors, like classes, is the easiest way to filter items. Each item can have several classes to be identified:
<div class="grid">
<div class="grid-item nonmetal">
<div class="grid-item noble-gas">
<div class="grid-item alkali metal">
<div class="grid-item alkaline-earth metal">
<div class="grid-item metalloid">
...
<div class="grid-item transition metal">
</div>
Additionally, you can use any element to filter items with the data attribute. In this case, <button>
and data-filter
:
<div class="button-group filter-group">
<button data-filter="*">All</button>
<button data-filter=".nonmetal">Nonmetals</button>
<button data-filter=".noble-gas">Noble Gases</button>
<button data-filter=".metal">Metals</button>
<button data-filter=".alkali.metal">Alkali Metals</button>
<button data-filter=".metalloid">Metalloids</button>
</div>
JavaScript
Set a selector with the filter
option. Items matching a filter will be shown, otherwise will be hidden.
//Filter metal items
mgnt.arrange({filter: '.metal'});
To filter items when a button is clicked, use the value in data-filter
attribute for the filter
option.
//Filter items on button click
const filterGroup = document.querySelector('.filter-group');
filterGroup.addEventListener('click', e => {
let filter = e.target.getAttribute('data-filter');
mgnt.arrange({filter: filter});
});
jQuery
Set a selector with the filter
option. Items matching a filter will be shown, otherwise will be hidden.
//Filter metal items
$('.grid').magnet({filter: '.metal'});
//Filter nonmetal or noble gas items
$('.grid').magnet({filter: '.nonmetal, .noble-gas'});
//Filter alkali and metal items
$('.grid').magnet({filter: '.alkali.metal'});
//Show all items
$('.grid').magnet({filter: '*'});
To filter items when a button is clicked, use the value in data-filter
attribute for the filter
option.
//Filter items on button click
$('.filter-group').click(function() {
var filter = $(this).data('filter');
$('.grid').magnet({filter: filter});
});
Items can be filtered using a function. The function requires a parameter elem
, which is the item element selector, and must return the data.
$('.grid').magnet({
filter: function(elem) {
//Get text from .symbol element
var symbol = $(elem).find('.symbol').text();
//Return elements with one character symbol
return symbol.match(/^[A-Z]$/);
}
});