jquery UI Sortable with table and tr width

Viewed 89721

I am using jQuery UI sortable to make my table grid sortable. The code seems to work fine but because I am not adding width to tds, when I drag the tr it shrinks the content.

For example; if my table row is 500px when I start dragging, it becomes 300px. I assume that's happening because no width is defined in the grid. That's because I am using two classes for the tds (fix and liquid).

The fix class makes the td equal to the content width and liquid makes the td width 100%. It's my approach for grid table without having to assign width to tds.

Any idea how to make sortable work with my approach?

13 Answers

jsFiddle

After a lot of different attempts I just tried a simple solution which completes the solution of Dave James Miller to prevent the table of shrinking while dragging the largest row. I hope it will helps :)

// Make sure the placeholder has the same with as the orignal
var start = function(e, ui) {
    let $originals = ui.helper.children();
    ui.placeholder.children().each(function (index) {
        $(this).width($originals.eq(index).width());
    });
}
// Return a helper with preserved width of cells
var helper = function(e, tr) {
    let $helper = tr.clone();
    let $originals = tr.children();
    $helper.children().each(function (index) {
        $(this).width($originals.eq(index).outerWidth(true));
    });
    return $helper;
};
.sortable({
    helper: function (e, ui) {
        ui.children().each(function () {
            $(this).width($(this).width());
        });
        return ui;
    }
});

I've also search for a solution and finally it's here:

You have to add to your style

.ui-sortable-helper {
  display: table;
}

and when declare the sortable

$('#sortable').sortable({
  helper: function (e, tr){
      var myHelper = [];
      myHelper.push(<tr style="width:' + $('#sortable').first('tr').width() + '">);
      myHelper.push($(tr).html());
      myHelper.push('</tr>');
      return myHelper.join('');
    }
});

So you can set the percentage with of td without problems!

$(function() {
    $( "#sort tbody" ).sortable({
        update: function () {
                                var order = $(this).sortable("toArray").join();
                                $.cookie("sortableOrder", order);
                        }
    });
    if($.cookie("sortableOrder")){
        var order = $.cookie("sortableOrder").split(",");
        reorder(order, $("#sort tbody"));
    }
    function reorder(aryOrder, element){
      $.each(aryOrder, function(key, val){
              element.append($("#"+val));
      });
    }
  });

Apply the sortable to the table's tbody element and just set the helper to 'clone', as described in jquery-ui's API

$("$my-table-tbody").sortable({
    helper: "clone"
});
Related