Adam Pietrasiak
Adam Pietrasiak

Reputation: 13184

jQuery UI: Draggable clone and change clone

I've got button <div class='button' data-tag='h1'>Drag to insert h1 tag</div>

When you drag it I want button to stay where it was, helper to be <h1>Example</h1> and where you drop it, you'll drop h1 tag without any draggable or jQuery UI styles.

So:

You drag something from button > you've got h1 tag in air, you drop unstyled h1 tag.

I've got this:

        var html = "<h1>Example</h1>";
        $('.button').draggable({
            connectToSortable: '.drop-area',
            containment: 'document',
            helper: function(){ return $(html); }
        });

And it makes helper to be h1 tag, but when I drop it, dropped item is button, not h1 tag.

In other words I've got a lot of buttons with various html tags or structures. Those buttons displays only name of tag and when you drag it, you see real tag to be dropped.

Upvotes: 2

Views: 7400

Answers (1)

Irvin Dominin
Irvin Dominin

Reputation: 30993

In your drop function you can access the original dragged item using ui.draggable, so you can clone it and append it into the droppable element.

Quick ref:

draggable - Type: jQuery - A jQuery object representing the draggable element.

helper - Type: jQuery - A jQuery object representing the helper that is being dragged.

Docs: http://api.jqueryui.com/droppable/#event-drop

Code:

$(function () {
    var html = "<h1>Example</h1>";
        $('.button').draggable({
            connectToSortable: '.drop-area',
            containment: 'document',
            helper: function(){ return $(html); }
        });
    $("#droppable").droppable({
        drop: function (event, ui) {
            $(ui.draggable).clone().appendTo(this);
            $(ui.draggable).remove();
        }
    });
});

Demo: http://jsfiddle.net/IrvinDominin/Cp6Rr/

Upvotes: 1

Related Questions