MatthewK
MatthewK

Reputation: 476

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/

Upvotes: 7

Views: 15464

Answers (3)

lmcDevloper
lmcDevloper

Reputation: 332

In my case, work fine these example:

$("[drag='true']").draggable({
    drag: handleDragDrag,
    start: handleDragStart,
    stop: handleDragStop,
    helper: 'clone',
    appendTo: 'body'
})
function handleDragStart(ev, ui) {
    $(this).show();
}
function handleDragDrag(ev, ui) {
}
function handleDragStop(ev, ui) {
    $(this).show();
}

Upvotes: 0

RYFN
RYFN

Reputation: 3069

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);
        }
    });

Upvotes: 10

Ian Robinson
Ian Robinson

Reputation: 16944

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.

Upvotes: 4

Related Questions