Search code examples
javascriptjqueryjquery-uijquery-ui-draggablejquery-ui-droppable

jQuery UI draggable grid


OK, what I want to create is: draggable elements which fit in table cells (.slot divs). Here is a simplified version of my code with jQuery UI:

<style>

.draggable, .cell  {
    width: 100px; height: 100px;
}

.cell {
    background: #F00;
}

</style>

<script type="text/javascript">

$(function() {
        $( ".draggable" ).draggable({ 
            distance: 20, 
            containment: "#container", 
            snap: ".slot", 
            snapMode: "inner", 
            snapTolerance: 10, 
        });
    });

</script>

<table id=”container”>
<tr>
    <td class=”cell”> <div class=”slot”> <div class=”draggable”></div> </div> </td>
    <td class=”cell”> <div class=”slot”></div> </td>
</tr>
<tr>
    <td class=”cell”> <div class=”slot”> <div class=”draggable”></div> </div> </td>
    <td class=”cell”> <div class=”slot”></div> </td>
</tr>
<tr>
    <td class=”cell”> <div class=”slot”></div> </td>
    <td class=”cell”> <div class=”slot”></div> </td>
</tr>
</table>

Since now I am able to move them around the cells (.slot) but I can’t achieve two things:

  1. Fit the draggables only in the “.slot”s (remove the option of abandoning a dragged element among the cells). Basically when you drop the dragged element it goes in the nearest cell or the one which covers most.
  2. Restrict putting of two draggables in one cell (.slot).

Any suggestions or help is appreciated!

Thanks in advance, George


Solution

  • Try using jQuery UI Sortable instead of Draggable. You may need to use Sortable-Connected Lists in your case.