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

Dynamically setting an appendTo target


Here is my fiddle.

In the jqueryUI draggable properties, how can I set the appendTo target dynamically, based on which element I am dropping my element ?

HTML:

<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
<div id="assets">
     <h4>Drag these to the red box</h4>

    <div class="asset">A1</div>
    <div class="asset">A2</div>
    <div class="asset">A3</div>
    <div class="asset">A4</div>
</div>

CSS:

#header, #content, #footer {
    height: 150px;
    width: 50%;
    border: 1px solid red;
    position: relative;
    float: left;
    margin: 20px;
}
#assets {
    position: fixed;
    top: 0;
    right: 0;
}
.asset {
    border: 1px solid blue;
    width: 50px;
    height: 50px;
}
.drop {
    background-color: pink;
}

JavaScript:

$('.asset').draggable({
    /*If we change appendTo to our #target dropzone, it works fine*/
    appendTo: 'body', //Try it with either #header, #content, #footer
    helper: 'clone'
});
$("#header, #content, #footer").droppable({
    hoverClass: "drop",
    drop: function (event, ui) {
        console.log('dropped');
        var element = $('<div class="asset">' + ui.draggable.text() + '</div>');
        element.css('top', ui.position.top);
        element.css('left', ui.position.left);
        element.css('position', 'absolute');
        $(element).appendTo(this);
    }
});

Solution

  • Note that the elements are placed in the right div. The problem are this few lines:

        element.css('top', ui.position.top);
        element.css('left', ui.position.left);
        element.css('position', 'absolute');
    

    If you remove them, you can even see that the elements are placed in the div you have dropped them. However, you can write this:

        element.css('top', ui.position.top - $(this).position().top - 21); // 20px margin + 1px border
        element.css('left', ui.position.left - $(this).position().left - 21);
        element.css('position', 'absolute');
    

    And it will work. :)