user935143
user935143

Reputation: 564

Can I drag an item from one accordion to another?

Is it possible to add an item to an accordion-control by dragging it from another accordion?

  1. I created an accordion named MainAccordion
  2. I created another accordion named MenuAccordion
  3. I want to drag item from MenuAccordion to MainAccordion

Upvotes: 1

Views: 2203

Answers (1)

vinczemarton
vinczemarton

Reputation: 8156

This is possible, though you may need to code a little. I have whipped up a fiddle for you: http://jsfiddle.net/LfaRk/1/

Let's go through it. The HTML is simple, same with the CSS.

The JavaScript:

$(function () {
    $("#catalog").accordion();
    $("#catalog2").accordion();
    $("#catalog h2").draggable({
        appendTo: "body",
        helper: "clone"
    });
    $("#catalog2").droppable({
        drop: function (event, ui) {
            var content = ui.draggable.next();
            ui.draggable.draggable('disable').appendTo(this);
            content.appendTo(this);
            $("#catalog").accordion('destroy').accordion();
            $("#catalog2").accordion('destroy').accordion();
        }
    });
});

So what am I doing?

  • I'm initializing the 2 accordions, with .accordion().
  • I'm making the headers of the first accordion draggable.
  • I'm making the second accordion droppable.

(The code I have started off on is: http://jqueryui.com/droppable/#shopping-cart, you should check it out too)

Let's see the drop callback on the second accordion:

drop: function (event, ui) {
    var content = ui.draggable.next();
    ui.draggable.draggable('disable').appendTo(this);
    content.appendTo(this);
    $("#catalog").accordion('destroy').accordion();
    $("#catalog2").accordion('destroy').accordion();
}

What is happening here?

The ui.draggable is the jQuery wrapped element that is dragged at the moment. I will need to insert it into the second accordion. Therefore I could call ui.draggable.appendto(this), but it will remain draggable, so I need to make it non draggable too.

I need to move the content with the header, so I select the content with: var content = ui.draggable.next() and then move it with: content.appendTo(this);. this is still the element which is droppable (the second accordion).

Finally I need to reinitialize the accordions, so that the elements recognise where they are:

$("#catalog").accordion('destroy').accordion();
$("#catalog2").accordion('destroy').accordion();

And it's ready.

If you want to make the items draggable back and forth you might need to code a little more. Also if you want the accordions to be sortable, droppable and sortable seems to interact in funny ways, so a little experimenting might be needed.

Upvotes: 3

Related Questions