Elementals.js

Latest Version: 2.0 RC 3 14 March 2017

Using _.uSortElement with UL or OL

View the Demo live here

_.uSortElement 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

_.uSortElement(_d.getElementById('sortList'), function(a, b) {
	return _.compareString(a.data, b.data);
});

Leveraging elementals.js' _.compareString 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

var
	sortList = _d.getElementById('sortList'),
	sortControls = _.make('#sortControls.controls', {
		after : sortList
	});
	
_.make('button', {
	type : 'button',
	content : 'Sort Ascending',
	onclick : function(e) {
		_.uSortElement(sortList, function(a,b) {
			return _.compareString(a.data, b.data);
		});
	},
	last : sortControls
});
_.make('br', { last : sortControls });

_.make('button', {
	type : 'button',
	content : 'Sort Descending',
	onclick : function(e) {
		_.uSortElement(sortList, function(a,b) {
			return _.compareString(b.data, a.data);
		});
	},
	last : sortControls
});
_.make('br', { last : sortControls });

_.make('button', {
	type : 'button',
	content : 'Original Order',
	onclick : function(e) {
		_.uSortRestore(sortList);
	},
	last : sortControls
});

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 _.uSortElement as mentioned above, with our different sort methods and Object.data.