Javascript solution to sorting an HTML table using JQuery UI sortable
A Pen by Marcel O'Neil on CodePen.
<table> | |
<tr> | |
<td>1</td> | |
<td>2</td> | |
<td>3</td> | |
</tr> | |
<tr> | |
<td>4</td> | |
<td>5</td> | |
<td>6</td> | |
</tr> | |
<tr> | |
<td>7</td> | |
<td>8</td> | |
<td>9</td> | |
</tr> | |
</table> |
Javascript solution to sorting an HTML table using JQuery UI sortable
A Pen by Marcel O'Neil on CodePen.
$('table').sortable({ | |
items: 'td', | |
helper: 'clone', | |
placeholder: 'placeholder', | |
change: function(evt, ui) { | |
for (var i = 0; i < 3; i++) {; | |
if ($('tr:eq(' + i + ')').children('td:not(.ui-sortable-helper):visible').length < 3) { | |
for (var j = 0; j < 3; j++) { | |
if ($('tr:eq(' + j + ')').children('td:not(.ui-sortable-helper):visible').length > 3) { | |
if (j > i) { | |
$('tr:eq(' + j + ')').children('td:not(.ui-sortable-helper):visible:first').detach().appendTo('tr:eq(' + i + ')'); | |
$('tr:eq(' + i + ')').children('td.ui-sortable-helper').detach().appendTo('tr:eq(' + i + ')'); | |
} else { | |
$('tr:eq(' + j + ')').children('td:not(.ui-sortable-helper):visible:last').detach().prependTo('tr:eq(' + i + ')'); | |
} | |
} | |
} | |
} | |
} | |
} | |
}).disableSelection(); |
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> |
td { | |
width: 100px; | |
height: 100px; | |
background: grey; | |
font-size: 15pt; | |
font-family: Helvetical, Arial, sans-serif; | |
color: white; | |
line-height: 100px; | |
vertical-align: middle; | |
text-align: center; | |
} | |
.placeholder { | |
width: 94px; | |
height: 94px; | |
background: none; | |
border: 3px dashed red; | |
} |