Skip to content

Instantly share code, notes, and snippets.

@ntkog
Last active July 12, 2019 09:33
Show Gist options
  • Save ntkog/f5b0931b9b82b08aa208 to your computer and use it in GitHub Desktop.
Save ntkog/f5b0931b9b82b08aa208 to your computer and use it in GitHub Desktop.
Sort Tables by columns with flexbox and a little Javascript
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<style>
#container {
flex-shrink: 0;
flex-basis: auto;
display: flex;
flex-direction: column;
height: 90%;
margin: 2em;
border: 2px dotted grey;
padding: 0.5em;
}
.row {
flex-flow : row nowrap;
display: flex;
order: 1;
}
.item {
flex: 1;
}
.row.header {
background-color: skyblue;
order: -1;
}
</style>
<div id="container">
<div class="row header">
<div class="item" data-field="nombre">Nombre</div>
<div class="item" data-field="apellidos">Apellidos</div>
<div class="item" data-field="telefono">telefono</div>
</div>
<div class="row">
<div class="item" data-nombre="Jorge">Jorge</div>
<div class="item" data-apellidos="Barrachina">Barrachina</div>
<div class="item" data-telefono="91443456">91443456</div>
</div>
<div class="row">
<div class="item" data-nombre="Susana">Susana</div>
<div class="item" data-apellidos="García">García</div>
<div class="item" data-telefono="91223456">91223456</div>
</div>
<div class="row">
<div class="item" data-nombre="Pedro">Pedro</div>
<div class="item" data-apellidos="Ramirez">Ramirez</div>
<div class="item" data-telefono="91573456">91223456</div>
</div>
<div class="row">
<div class="item" data-nombre="Alba">Alba</div>
<div class="item" data-apellidos="Lopez">Lopez</div>
<div class="item" data-telefono="91833456">91833456</div>
</div>
<div class="row">
<div class="item" data-nombre="Ramón">Ramón</div>
<div class="item" data-apellidos="Casco">Casco</div>
<div class="item" data-telefono="91653456">91653456</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded",init,false);
function init () {
var container = document.getElementById('container');
container.onclick = function (e) {
var selected = e.target;
var filter = selected.dataset.field;
[].slice.call(container.querySelectorAll('[data-' + filter +']')).sort(function(a,b){ return (a.dataset[filter].toLowerCase() > b.dataset[filter].toLowerCase()) - (a.dataset[filter].toLowerCase() < b.dataset[filter].toLowerCase()); }).map(function(n,i){ n.parentElement.style.order = i+1; return n;});
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment