Sanya
Sanya

Reputation: 1280

JQUERY Drag and Clone across divs

I have a box that when the user clicks (holds) a clone of the box must be created and that clone needs to be draggable. Then the user carries the cloned red box over to the black box to drop it in. I'm using JQuery 1.9.1 and JQuery UI and I still can't seem to get this right. Can someone help?

Here's a jsFiddle

HTML

<div id='main'>
    <div id='left'>
      <div id='box'></div>
    </div>
    <div id='right'>
        <div id='thespace'>Place in here</div>
    </div>
</div>

JQUERY

$(document).ready(function() {
    $('#box').draggable({helper: "clone"});
    $('#box').bind('dragstop', function(event, ui) {
        $(this).after($(ui.helper).clone().draggable().css('z-index','99999'));
    });
});

Here's a jsFiddle

Upvotes: 4

Views: 2781

Answers (2)

pierdevara
pierdevara

Reputation: 406

Here's a working solution, not sure if it's the best. I append the current box to the new container, and add a clone to the original position, rebinding the listener.

var dragConfig = {
        start: function(){
            initialBox = $(this).clone();
            initialBox.draggable( dragConfig );
        },
        stop: function(){
            $(this).appendTo("#"+currentHoverID);
            initialBox.appendTo("#left");
        }
    };

Working jsfiddle: http://jsfiddle.net/WEtr4/3/

Upvotes: 2

DarkAjax
DarkAjax

Reputation: 16223

JavaScript:

$('.box').draggable({
    helper: "clone"
}).on('dragstart', function (e, ui) {
    $(ui.helper).css('z-index','999999');
}).on('dragstop', function (e, ui) {
    $(this).after($(ui.helper).clone().draggable());
});

CSS:

.box{width:100px;height:100px;background-color:red;left:50px;top:50px;}

I changed the ID to a Class because cloning the element would result in having a bunch of red squares with the same ID which is not good at all, and also removed the absolute positioning of the initial square, because it affected the clones...

Working JSFiddle Demo

Upvotes: 3

Related Questions