JSFiddle - React, Tailwind, and code Playground
by Joshua
HTML
Order By: <button id="abc">a-z</button> |
<button id="dist">distance</button>
<br />
<main>
<section data-state="ms" data-dist="1">ms</section>
<section data-state="al" data-dist="389">al</section>
<section data-state="fl" data-dist="3">fl</section>
</main>
CSS
main {
display: flex;
}
JavaScript
$.fn.flexboxGridSort = function(reordering, _reverse, _animate){
// ITERATE GRIDS
this.each(function(){
var $children = $(this).children(),
$table = {},
sorted_keys;
// IF REORDERING IS SET, GET THE DATA
if(reordering !== undefined && reordering !== null){
$table = {};
$(this).children().each(function(){
var key = reordering.call(this);
if(!$table[key])$table[key] = [];
$table[key].push(this);
});
// RESORT KEYS
sorted_keys = Object.keys($table).sort();
if(_reverse)sorted_keys = sorted_keys.reverse();
// RESORT VALUES
$children = Array.prototype.concat.apply(
[],
sorted_keys.reduce(function (result, key) {
result.push($table[key]);
return result;
}, [])
);
}
// GET POSITIONS, SET ORDER, GET NEW POSITIONS, AND CALLBACK
$($children).each(function(i){ $(this).css('order', i+1); });
});
};
$('#abc').click(function(){
$('main').flexboxGridSort(function(){
return $(this).attr('data-state');
});
});
$('#dist').click(function(){
$('main').flexboxGridSort(function(){
return $(this).attr('data-dist');
});
});