You can order the elements with a function you supply. In the demo above, each item has a data-date-created
and data-title
attribute. When the select option menu changes, a sort object is passed to shuffle.
<figure class="picture-item" data-groups='["photography"]' data-date-created="2010-09-14" data-title="Baseball">…</figure>
<select class="sort-options">
<option value="">Default</option>
<option value="title">Title</option>
<option value="date-created">Date Created</option>
</select>
Demo.prototype.addSorting = function () {
document.querySelector('.sort-options').addEventListener('change', this._handleSortChange.bind(this));
};
Demo.prototype._handleSortChange = function (evt) {
var value = evt.target.value;
var options = {};
function sortByDate(element) {
return element.getAttribute('data-created');
}
function sortByTitle(element) {
return element.getAttribute('data-title').toLowerCase();
}
if (value === 'date-created') {
options = {
reverse: true,
by: sortByDate,
};
} else if (value === 'title') {
options = {
by: sortByTitle,
};
}
this.shuffle.sort(options);
};
The options
object can contain three properties:
reverse
: a boolean which will reverse the resulting order.by
: a function with an element as the parameter. Above, we’re returning the value of the data-date-created
or data-title
attribute.randomize
: Make the order random.Returning undefined
from the by
function will reset the order to DOM order.
Calling sort with an empty object will reset the elements to DOM order.
Check out the demo.