Example

Here is a simple example of a group of divs that can be sorted either by their HTML content or by custom attribute values:

Sort alphabetically by HTML content

Sort low to high by the value of the attribute "sortweight"

Pears [sortweight: 5]
Apples [sortweight: 3]
Cherries [sortweight: 1]
Oranges [sortweight: 4]
Strawberries [sortweight: 2]

Code

There are only a few requirements for this code to work: There has to be a container element that holds all the sortable divs and all the divs share a classname. Also, this example uses MooTools and its $ and $$ functions as well as Element.dispose() and Element.inject(), but this should be easy to change to jQuery or other frameworks.

HTML:


<div id="sortexample">
	<div class="sortitem" sortweight="5">Pears [sortweight: 5]</div>
	<div class="sortitem" sortweight="3">Apples [sortweight: 3]</div>
	<div class="sortitem" sortweight="1">Cherries [sortweight: 1]</div>
	<div class="sortitem" sortweight="4">Oranges [sortweight: 4]</div>
	<div class="sortitem" sortweight="2">Strawberries [sortweight: 2]</div>
</div>
						

JavaScript:


// sort all divs with classname 'sortitem' by html content
function sort_div_content() {
	// copy all divs into array and destroy them in the page
	divsbucket = new Array();
	divslist = $$('div.sortitem');
	for (a=0;a<divslist.length;a++) {
		divsbucket[a] = divslist[a].dispose();
	}

	// sort array by HTML content of divs
	divsbucket.sort(function(a, b) {
		if (a.innerHTML.toLowerCase() === b.innerHTML.toLowerCase()) {
			return 0;
		}
		if (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) {
			return 1;
		} else {
			return -1;
		}
	});

	// re-inject sorted divs into page
	for (a=0;a<divslist.length;a++) {
		divsbucket[a].inject($('sortexample'));
	}
}

// sort by attributes - usage for our example: sort_div_attribute('sortweight');
function sort_div_attribute(attname) {
	// copy all divs into array and destroy them in the page
	divsbucket = new Array();
	divslist = $$('div.sortitem');
	for (a=0;a<divslist.length;a++) {
		divsbucket[a] = new Array();
		// we'vev passed in the name of the attribute to sort by
		divsbucket[a][0] = divslist[a].get(attname);
		divsbucket[a][1] = divslist[a].dispose();
	}

	// sort array by sort attribute content
	divsbucket.sort(function(a, b) {
		if (a[0].toLowerCase() === b[0].toLowerCase()) {
			return 0;
		}
		if (a[0].toLowerCase() > b[0].toLowerCase()) {
			return 1;
		} else {
			return -1;
		}
	});

	// re-inject sorted divs into page
	for (a=0;a<divslist.length;a++) {
		divsbucket[a][1].inject($('sortexample'));
	}
}
						

Discussion

Name *:        Email *:        URL:
SUBMIT
no comments yet...