JQueryUI: correctly removing a draggable item

I am working on a visual editor that requires elements that the user can add, delete and drag as they wish. Each element is a div that can be dragged using jQueryUI. New elements are added to the parent div , which represents the workspace. Each item has a button inside it to remove it. All of this works great.

The problem I am facing is that when I delete an item that was not created last, all other draggable items change position. This is apparently caused by relocatable elements using relative positioning.

At the moment, my delete function simply calls $('#item-x').remove() . Is there any other way to remove drag and drop items?

+7
source share
3 answers

Turns out this question is a duplicate of this , but I was looking for the wrong thing.

The solution is simply to change the elements in order to have absolute positioning, in accordance with another question. However, I found that my elements will always return to relative positioning, even when I point out in their CSS that they should be absolute, so now I do:

 $('#item-x').draggable().css("position", "absolute"); 
+3
source

Try using .draggable("destroy") instead. I used it just fine.

You can view this method and all other methods, parameters and events in jqueryUI Draggable destroy

Update

Sorry, I thought your problem was something else. You need to change the approach, since removing an element from dom is not actually related to the fact that the element is draggable . You need to encapsulate your draggable element, such as a div with the same height and width as your draggable, and then just destroy the draggable as you like.

HTML:

 <div id="conteiner"> <div class="dragConteiner"><div id="draggable1" class="draggable"></div></div> <div class="dragConteiner"><div id="draggable2" class="draggable"></div></div> <div class="dragConteiner"><div id="draggable3" class="draggable"></div></div> </div> 

JQuery

 $(function(){ $("#draggable1").draggable(); $("#draggable2").draggable(); $("#draggable3").draggable(); $("#draggable2").on('mouseup',function(){ alert('bye draggable!'); $(this).draggable('destroy'); //in case you like to use if after //$(this).hide(); //as in your code $(this).remove(); }) }) 

CSS

 .draggable{ height:50px; width:50px; background: green; } .dragConteiner{ height:50px; width:50px; margin-top:5px; } #conteiner{ margin-top:25px; margin-left:25px; } 

Jsfiddle example

+7
source

For some reason, the destroy function does not work. If you want to completely remove the drag property from the element, try this

 var temp = $("#dragItem").draggable().remove(); 

Gets the item by removing the draggable property. Grab the temporary variable and return it to the parent

 $(temp).appendTo("#parentContainer") 

Let me know if this works.

+1
source

All Articles