Sorting Faux-Columns (and real table columns too) with jQuery
There might come a time where an HTML table can’t be used but the faux-columns need to be sorted.

The example image above shows, on the left, unsorted columns and, on the right, sorted columns.
The HTML for this fake columns example is a table-less group of divs as follows:
<style type="text/css">
.row {clear:both}
.column {width:100px;height:150px;margin:5px;float:left}
.header{background:#000; color:#fff;}
.group1, .group4 {background-color:#F00}
.group2, .group5 {background-color:#6C6}
.group3, .group6 {background-color:#06C}
.hover {background-color:purple};
</style>
<div class="row">
<div class="header">My Header</div>
<div class="group1 column">group1</div>
<div class="group2 column">group2</div>
<div class="group3 column">group3</div>
<div class="group4 column">group4</div>
<div class="group5 column">group5</div>
<div class="group6 column">group6</div>
</div>
<div class="row">
<div class="group1 column">group1</div>
<div class="group2 column">group2</div>
<div class="group3 column">group3</div>
<div class="group4 column">group4</div>
<div class="group5 column">group5</div>
<div class="group6 column">group6</div>
</div>
<div class="row">
<div class="group1 column">group1</div>
<div class="group2 column">group2</div>
<div class="group3 column">group3</div>
<div class="group4 column">group4</div>
<div class="group5 column">group5</div>
<div class="group6 column">group6</div>
</div>
<div class="row">
<div class="header">My Header 2</div>
<div class="group1 column">group1</div>
<div class="group2 column">group2</div>
<div class="group3 column">group3</div>
<div class="group4 column">group4</div>
<div class="group5 column">group5</div>
<div class="group6 column">group6</div>
</div>
Notice that the HTML uses classes like row and column to create faux rows and columns.
Using a little bit of jQuery, the following JavaScript can sort the faux columns:
// include jQuery library first
// row selector, col selector, order array
function sortCols(row, col, order){
$(row).each(function(){
var tmp = {};
$(this).children(col).each(function(cindex){
tmp[cindex] = $(this).detach();
});
for(i in order){
$(this).append( tmp[order[i]] );
}
});
}
Running the following function will sort the columns while keeping all bindings:
Use regular jQuery selectors and an array of positions as parameters. You can specify the selector classes for rows and columns and the function will take care of the rest. In the example below, columns 3 will be first, 6 will be second, and so on…
// parameters are: row selector, col selector, order array
sortCols(".row", ".column", [2,5,0,3,4,1]);
But wait! It also works on tables!!
sortCols("tr", "td", [2,5,0,3,4,1]);-
howardtharp liked this
-
rankandfile liked this
-
andresvidal posted this
