You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
2.4 KiB
HTML
58 lines
2.4 KiB
HTML
<h2>Sorting<a href="#sorting"></a></h2>
|
|
|
|
<p>You can order the elements with a function you supply. In the demo above, each item has a <code>data-date-created</code> and <code>data-title</code> attribute. When the select option menu changes, a sort object is passed to shuffle.</p>
|
|
|
|
<div class="code-block">
|
|
<pre rel="HTML"><code class="language-markup"><figure class="picture-item" data-groups='["photography"]' data-date-created="2010-09-14" data-title="Baseball">…</figure></code></pre>
|
|
</div>
|
|
|
|
<div class="code-block">
|
|
<pre rel="HTML"><code class="language-markup"><select class="sort-options">
|
|
<option value="">Default</option>
|
|
<option value="title">Title</option>
|
|
<option value="date-created">Date Created</option>
|
|
</select></code></pre>
|
|
</div>
|
|
|
|
<div class="code-block">
|
|
<pre rel="JavaScript"><code class="language-javascript">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);
|
|
};</code>
|
|
</div>
|
|
|
|
<p>The <code class="language-javascript">options</code> object can contain three properties:</p>
|
|
<ul>
|
|
<li><code class="language-javascript">reverse</code>: a boolean which will reverse the resulting order.</li>
|
|
<li><code class="language-javascript">by</code>: a function with an element as the parameter. Above, we’re returning the value of the <code class="language-markup">data-date-created</code> or <code class="language-markup">data-title</code> attribute.</li>
|
|
<li><code class="language-javascript">randomize</code>: Make the order random.</li>
|
|
</ul>
|
|
<p>Returning <code class="language-javascript">undefined</code> from the <code class="language-javascript">by</code> function will reset the order to DOM order.</p>
|
|
<p>Calling sort with an empty object will reset the elements to DOM order.</p>
|
|
<p class="demo-link-container">Check out the <a href="#demo">demo</a>.</p>
|