Сортировка колонок таблицы

by Denis

HTML

<table class="sort_col_table">
    <tr>
        <th>&lt;&lt; col 1 &gt;&gt;</th>
        <th>&lt;&lt; col 2 &gt;&gt;</th>
        <th>&lt;&lt; col 3 &gt;&gt;</th>
        <th>&lt;&lt; col 4 &gt;&gt;</th>
    </tr>
    <tr>
        <td>1a</td>
        <td>2a</td>
        <td>3a</td>
        <td>4a</td>
    </tr>
    <tr>
        <td>1b</td>
        <td>2b</td>
        <td>3b</td>
        <td>4b</td>
    </tr>
    <tr>
        <td>1c</td>
        <td>2c</td>
        <td>3c</td>
        <td>4c</td>
    </tr>
</table>

CSS

.sort_col_table {
    position: absolute;
    width: 400px;
    margin: 50px;
    border-collapse: collapse;
    z-index: 10;
}
th, td  {
    border: 1px solid #900;
    text-align: center;
}
th {
    cursor: move;
    font-weight: bold;
}
th:hover {
    background: #CCC;
}
td {
    width: 50px;
    height: 100px;
}
.clone_tbl {
    display: block;
    position: relative;
    margin: 0;
    left: 0;
    top: 0;
    color: #060;
    background: #FAEBD7;
    z-index: 20;
    
}
.clone_tbl li {
    list-style: none;
    float: left;
}

.container {
    position: absolute;
    background: #FAEBD7;
    z-index: 5;
}
.hightlight {
    background: #F0FFFF;
}

JavaScript

var tbl = $('.sort_col_table'); // это наша таблица
var numCols = tbl.find('th').length;
var cloneCol = '';
var totalTbls = '';
var i = j = 0;

$('<div class="container"></div>').insertAfter(tbl)
    .css({
        width: tbl.width() + 1,
        height: tbl.height(),
        top: tbl.offset().top,
        left: tbl.offset().left
    });

for(i = 0; i < numCols; i++){
    cloneCol += '<li><table></table></li>';
}
totalTbls = '<ul class="clone_tbl">' + cloneCol + '</ul>';
$('.container').append(totalTbls);

$('th,td').each(function(i){
    var ccc = $(this).clone(true, true);
    ccc.appendTo('.clone_tbl li:eq(' + j + ') table')
        .wrap('<tr>')
        .width($(this).width() - 1);
    j++;
    if(j >= numCols){
        j = 0;
    }
});

// Скрываем оригинальную таблицу
tbl.hide();
// Запускаем сортировку
$('.clone_tbl').sortable({
    handle:'th',
    start: function(e, ui) {
        ui.item.addClass('hightlight');
    },
    stop: function(e, ui) {
        ui.item.removeClass('hightlight');
        ui.item.effect('pulsate',{times: 3});
    }
}).disableSelection();;