Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When cloning a draggable object in jQuery UI, how can you transfer the data and events to the new element?

I have a draggable element with the helper: 'clone' set, but when it clones the element, none of the data() or events are persistent in the new element.

I've tried a number of ways to reattach the data(), but I can't seem to select the new element as well as the old element in the same statement.

For instance, I can select the initial element in the draggable stop() event:

$blah.draggable({
    helper: 'clone',
    stop: function(ev, ui) {
        var oldData = $(ev.target).data('blah');
    }
});

And I can also get the new element in the droppable drop() event:

$blah.droppable({
    drop : function(ev, ui) {
        var $newElement = ui.draggable;
    }
});

But I can't figure out a way to get both in the same event.

What I'd like to do is somehow transfer the data, e.g.:

$newElement.data('blah', $oldElement.data('blah'));

Or otherwise make the data persistent, like you can with $blah.clone(true);

like image 663
Jon Raasch Avatar asked Jun 17 '11 22:06

Jon Raasch


2 Answers

To get access to the data of original element in drop you can use ui.draggable.context. In the example below context would refer to the original dragged element and you have access to all of its content. Draggable refers to the new element that is being dropped.

$("#droppable").droppable({
    drop: function(ev, ui) {        
        console.log(ui);
        console.log(ui.draggable.context);
        console.log($(ui.draggable.context).data('pic'));
    }
});
like image 63
Alex Achinfiev Avatar answered Oct 12 '22 14:10

Alex Achinfiev


I haven't worked too extensively with droppable, but couldn't you just do something like this?

$(".draggable").draggable({
    helper: 'clone'
});

$("#droppable").droppable({
    drop: function(ev, ui) {
        $(this).append(ui.draggable.clone(true));
    }
});

Seems to work unless there's something I'm missing:

http://jsfiddle.net/hasrq/

like image 24
James Montagne Avatar answered Oct 12 '22 13:10

James Montagne