Drag'n'drop HTML table columns

by Juan Muñoz

HTML

<button id="getSorting">Get sorting</button><input id="showSorting" />
<table id="table1">
    <thead class="ui-state-default">
    </thead>
    <tbody>
    </tbody>
</table>

JavaScript

$(function() {
    var $table1 = $('#table1');
    var $table1Thead = $table1.find('thead');
    var $table1Tbody = $table1.find('tbody');
    var startPos;
    var oldPos;
    
    // populate fake data
    var maxCols = 10;
    var maxRows = 50;
    for (var i = 1; i <= maxCols; i++) {
        $table1Thead.append('<th sort="' + i + '" id="column[' + i + ']">column ' + i + '</th>');
    }
    var rowHtml;
    for (var x = 1; x <= maxRows; x++) {
        rowHtml = '<tr>';
        for (var i = 1; i <= maxCols; i++) {
            //rowHtml += '<td>' + i + ' - ' + x + '</td>';
            rowHtml += '<td>col ' + i + '</td>';
        }
        rowHtml += '</tr>';
        $table1Tbody.append(rowHtml);
    }
    
    // Show sorting
    $("button#getSorting").click(function() {
        $('#showSorting').val($table1Thead.sortable('toArray', { attribute: "sort" } ))
        console.log($table1Thead.sortable('toArray', { attribute: "sort" } ))
    })
    
    // The sorting
    $table1Thead.sortable({
        axis: "x" ,
        items: 'th',
        containment: 'parent',
        cursor: 'move',
        helper: 'clone',
        distance: 5,
        opacity: 0.5,
        placeholder: 'ui-state-highlight',
        start: function(event, ui) {
            startPos = $table1Thead.find('th').index(ui.item);
            oldPos = startPos;
        },
        change: function(event, ui) {            
            // Get position of the placeholder
            var newPos = $table1Thead.find('th').index($table1Thead.find('th.ui-state-highlight'));

            // If the position is right of the original position, substract it by one in cause of the hidden th
            if(newPos>startPos)newPos--;

            // move all the row elements
            //console.log('Move: 'oldPos+' -> '+newPos);
            $table1Tbody.find('tr').find('td:eq(' + oldPos + ')').each(function() {
                var tdElement = $(this);
                var tdElementParent = tdElement.parent();
       ...