31
votes

When using jQuery UI draggables and droppables, how do you change the dragged-and-dropped element on drop? I am trying to drag one DIV to another sortable DIV. On drop, I'd like to change the classes on the dropped DIV and change its innerHTML content.

After reading various StackOverflow questions, my code looks like this:

$(".column").droppable({
  accept: '.element-dragging', 
    drop: function(event, ui) {
        if ($(ui.draggable).hasClass("elemtxt")) {
            $(ui.draggable).replaceWith('<div class="element element-txt">This text box has been added!</div>');
        }
    }
})

It's not working for me. :-(

A full copy of my code is located at http://www.marteki.com/jquery/bugkilling.php.

1

1 Answers

53
votes

Taking the full javascript code from the link you gave, you can change it as follows to make it work:

$(function() {
    $(".elementbar div").draggable({
        connectToSortable: '.column',
        cursor: 'move',
        cursorAt: { top: 0, left: 0 },
        helper: 'clone',
        revert: 'invalid'
    });
    $(".elementbar div, .elementbar div img").disableSelection();
    $(".column").sortable({
        connectWith: '.column',
        cursor: 'move', 
        cursorAt: { top: 0, left: 0 }, 
        placeholder: 'ui-sortable-placeholder',
        tolerance: 'pointer',
        stop: function(event, ui) {
            if (ui.item.hasClass("elemtxt")) {
                ui.item.replaceWith('<div class="element element-txt">This text box has been added!</div>');
            }
        }
    });
    $(".element").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all");
});

There were a couple of issues:

  1. The drop event (that you show in your question) wasn't firing because you weren't accepting the right content.
  2. If you have both .sortable & .droppable you end up with weird double events firing. This is unnecessary anyway, since you can effectively grab the drop event from sortable's events given that you've linked it with the draggable.

One other thing to note - it would have been nicer to use the sortable's receive event instead of stop (since stop gets fired every time any sorting stops & receive is specifically there to fire when you drop a new item into the sort list), but it doesn't work properly because the item hasn't yet been added to the sortable list, so you aren't able to change it at that point. It works ok on stop simply because none of the other sortable items have the elemtxt class.