Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery draggable and appendTo doesn't work

I use jQuery ui draggable but the option appendTo doesn't work. However other option like containment or grid work properly. Here is the code:

HTML

<div id="demo">
</div>
<div id="sidebar">
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div> 
</div>

script

jQuery(".item").draggable({ appendTo: "#demo", grid: [ 10, 10 ], containment: "#demo" });

CSS

#demo {
    width: 500px;
    height: 500px;
    border: 1px solid black;
    float: left;
}
#draggable {
    background: red;
    width: 50px;
    height: 50px;
}
#sidebar {
    float: left;
    width: 300px;
}
.item {
    cursor: pointer;
    background: black;
    width: 100px;
    height: 100px;
    margin: 10px;
}

Here is a live demo: http://jsfiddle.net/fzjev/

like image 800
MatthewK Avatar asked Mar 10 '12 16:03

MatthewK


2 Answers

here's an open bug on the issue - Draggable: appendTo option doesn't work together with helper: 'original'.

The suggested workaround is to use helper: 'clone' and hide/show the original on drag start/stop.

e.g.

$('.draggyThing').draggable({
        appendTo: '.dropArea',
        helper: 'clone',
        start: function (event, ui) {
            $(this).hide();
        },
        stop: function (event, ui) {
            $(this).show();
        }
    });

You'll probably then want to manually append your draggables on drop of a droppable element.

 $('.dropArea').droppable({
        accept: '.draggyThing',
        drop: function (event, ui) {
            $('.dropArea').append(ui.draggable);
        }
    });
like image 72
RYFN Avatar answered Nov 29 '22 09:11

RYFN


It looks like for the appendTo option to be recognized the item being dragged has to be outside of the body.

From jQuery UI 1.8.18 (around line 275)

if(!helper.parents('body').length)
  helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

In your example the if statement evaluates to false, so the appendTo logic is not fired.

like image 34
Ian Robinson Avatar answered Nov 29 '22 08:11

Ian Robinson