3
votes

I have three blocks, "draggable", "sortable" and "droppable"

Inside "draggable" I have few elements built like this:

<li class="draggable ui-draggable ui-draggable-handle" id="header-1">
 <img src="http://placehold.it/150x100">
</li>

These elements can be dragged into "sortable" and the elements dragged here can be dropped into "droppable" which is removing them from "sortable" it's basically deleting them.

How can I replace the image dropped into "sortable" with a new one without replacing the image from "draggable"?

Here's what I've tried:

I've tried adding this to the "draggable":

start: function (event, ui) {
     $(this).addClass('testing');
 }

This is adding ".testing" class to the current dragged item.

and I've added this to the "sortable" :

     receive: function (event, ui) {
     $('.testing').replaceWith('<img src="http://placehold.it/400x300">');

The problem here is that is replacing the whole markup including the "li" parent and I want to replace just the "img" element.

Here is a jsbin of how this works now.

2

2 Answers

3
votes

Sorry for misunderstanding the question. What you've described is: modifying the dropped element without modifying the original draggable (let me know if I misunderstood again).

This is usually done using the helper option, typically with a function, but the helper: "clone" you have can also work. This will result in a clone of the draggable being dropped. That means you can just restrict your selectors to the current container, and you don't need the ".testing" class at all (though of course feel free to keep it if it makes it easier for you to see what's going on):

receive: function (event, ui) {
    $('.testing', this).replaceWith('<img src="http://placehold.it/400x300">');
    // or...
    $(this).find('.testing').replaceWith('<img src="http://placehold.it/400x300">');
    // or without the superfluous class...
    $(this).find('li.draggable').replaceWith('<img src="http://placehold.it/400x300">');
    // or to keep the li tags as per my original post's suggestion...
    $('li.draggable > img', this).replaceWith('<img src="http://placehold.it/400x300">');
}

Remember, jQuery's clone only makes a copy of the DOM node, none of its jQuery properties are preserved. The dropped helper will no longer be a draggable widget (though in your case you're using a sortable which will still let you drag it)

0
votes

On receive event, get previous dropped element. If this element exists append to sender.

$(".connect").on("sortreceive", function(event, ui) {
  var prevChild = $(event.target).children().not(ui.item);
  if(prevChild.length > 0){
    $(ui.sender).append(prevChild);
  }
});