Search code examples
jquerypositionjquery-ui-sortable

jquery sortable floated elements with percent chaos


After applying sortable to floated elements with percent based widths, dragging the last item of a row can "sometimes" cause the element to jump to the next row

This behaviour is only seen when the container is at particular widths... and thus has a random nature (mainly seen when applying sortable to responsive elements such as bootstrap styled columns)

See link below for a simple example... Dragging the orange box will highlight the issue:

JSFiddle

$(function() {
    $("#sortable").sortable();
});
#sortable{
    width:239px;
}
#sortable div {
    float:left;
    width:25%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

<div id="sortable">
  <div style="background-color:red">1</div>
  <div style="background-color:blue">2</div>
  <div style="background-color:green">3</div>
  <div style="background-color:orange">4</div>
</div>

It appears to only be an issue when the container width divided by columns has .75 remainder. E.g. a container with a width of 239px and items with widths of 25% (239/4 = 59.75).

The browser deals with the above example, but sortable appears to apply a fixed width to the placeholder (or/and helper) and thus chaos ensues.

I've submitted a bug with JQuery UI regarding this... But if anyone has any nice workarounds for the time being, I'd appreciate it.

Cheers.


Solution

  • You can specify to helper, which is dragged while sorting:

     $("#sortable").sortable({
         helper: 'clone'
     });
    

    So now the original div will be cloned for dragging, so jQuery don't need to create a new element, which obviously goes wrong.

    Unfortunately I don't know if there are other sideeffects or edge-cases, but it will work for your provided example.

    Demo

    Reference

    .sortable() - helper