Using _.USort.element with UL or OL
_.USort.element is one of the more powerful methods in the elementals.js library as it allows you to sort the contents of a TBODY
, UL
or OL
quickly and easily.
In the case of a UL or OL, it works the same way. If we have a list like this:
HTML
<ul id="sortList">
<li>Donnie was a little boy</li>
<li>sent off to military school,</li>
<li>now no matter what he does</li>
<li>he always plays the fool!</li>
</ul>
The JavaScript needed to make elementals sort that is:
JavaScript
_.USort.element(
document.getElementById('sortList'),
function(a, b) {
return _.Compare.string(a.data, b.data);
}
);
Leveraging elementals.js' _.compare.string function to handle the sort. The sort for a table behaves similar to a normal Array.uSort
except that the values passed to variables 'a' and 'b' are objects containing:
-
Object.tag -- a reference to the actual
LI
Element. - Object.data -- The text (without tags) contained in that row.
At any time you can restore the original order the page downloaded with by using:
JavaScript
_.USortRestore(_d.getElementById('sortTest'));
The complete demo makes use of the _.make method to create the scripting only buttons for testing out various different sorting methods. The scripting for that looks like this:
JavaScript
(function(d) {
var sortList = d.getElementById('sortList');
_.make('#sortControls.controls', {
content : [
[ 'button~Sort Ascending', {
type : 'button',
onclick : function(e) {
_.USort.element(sortList, function(a,b) {
return _.Compare.string(a.data, b.data);
});
}
} ], [ 'br' ],
[ 'button~Sort Descending', {
type : 'button',
onclick : function(e) {
_.USort.element(sortList, function(a,b) {
return _.Compare.string(b.data, a.data);
});
}
} ], [ 'br' ],
[ 'button~Original Order', {
type : 'button',
onclick : function(e) {
_.USort.restore(sortList);
}
} ]
],
after : sortList
});
})(document);
By making BUTTON
tags of type="button"
we don't have to trap/prevent event bubbling. (The default behavior for a BUTTON
is type="submit"
-- we don't want that!. We just give them an onclick handler that performs that same style _.USort.element as mentioned above, with our different sort methods and Object.data
.