akaRem
akaRem

Reputation: 7638

jquery-ui sortable: how not to add cells on dragging?

I have some table, For example:

<table class="table table-hover table-striped" id="mytable">
    <thead>
    <tr>
        <th>#</th>
        <th>Table heading 1</th>
        <th>Table heading 2</th>
        <th>Table heading 3</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>Table cell</td>
        <td>Table cell</td>
        <td>Table cell</td>
    </tr>
    </tbody>
</table>

Then I want to make sortable table's row-headers.

$('#mytable thead tr').sortable({
    axis: "x",
    helper: "clone"
}).disableSelection();

The Problem:

When I start Drag-n-Drop, I have 6 th-s instead of 4:

<tr class="ui-sortable">
    <th>#</th>
    <th style="
        display: none;">Table heading 1</th>
    <th class="ui-sortable-placeholder" 
        style="
            visibility: hidden;"></th>
    <th>Table heading 2</th>
    <th>Table heading 3</th>
    <th style="
            display: table-cell; 
            width: 343px; 
            height: 37px; 
            position: absolute; 
            z-index: 1000; 
            left: 184px;" 
        class="ui-sortable-helper">Table heading 1</th>
</tr>

..and all the mark-up starts being very unstable and uncertain: while I drag th item over table, I see all rows jumping in size.

It's evident that this happens because of count th items (which are not equal to number of td items in tr).

How to repair this?

Upvotes: 0

Views: 883

Answers (1)

Matt
Matt

Reputation: 335

Every time you start dragging it creates two new th elements. one is not displayed so it doesn't seem to effect anything. The second one is a placeholder for the original element while you drag it around. The width of this new element isn't set so it auto sizes to the columns largest width which appears to be whats causing it to jump around.

To counter this I changed the width of the placeholder element to the width of the element we are dragging in the start function. Hope this helps

start: function(event, ui){
    $(".ui-sortable-placeholder").css({width: $(ui.item).width()}); 

Below is the code and here's my fiddle

$(function () {
$('#mytable thead tr').sortable({
    axis: "x",
    helper: "clone",
    start: function(event, ui){
        $(".ui-sortable-placeholder").css({width: $(ui.item).width()});    
    }
}).disableSelection();
});

Upvotes: 1

Related Questions