Reputation: 7186
I'm working on a visual editor that requires elements the user can add, remove, and drag around as they like. Each element is a div
made draggable with jQueryUI. New elements are appended to a parent div
that represents the workspace. Each element has a button inside itself to remove it. This all works great.
The problem I'm having is that when I remove an element that was not the most recently created, all the other draggable elements change position. This seems to be caused by the draggable elements using relative
positioning.
At the moment, my removal function simply calls $('#item-x').remove()
. Is there another way I should be removing draggable elements?
Upvotes: 7
Views: 17894
Reputation: 1578
For some reasons destroy function is not working. If you want to completely remove the drag property from the element try this
var temp = $("#dragItem").draggable().remove();
This returns the element by removing the draggable property. Capture in a temp variable and assign it back to the parent element
$(temp).appendTo("#parentContainer")
Let me know if this works.
Upvotes: 1
Reputation: 7186
Turns out this question is a duplicate of this one, but I was searching for the wrong thing.
The solution is to simply change the elements to have absolute positioning, as per the other question. I found, however, that my elements would always revert to relative positioning even when I specified in their CSS that they should be absolute, so now I do:
$('#item-x').draggable().css("position", "absolute");
Upvotes: 3
Reputation: 2150
Try using .draggable("destroy")
instead. I have used it just fine.
You can view this method and all other methods, options and events at jqueryUI Draggable destroy
Update
Sorry i thought your problem was something else. What you need to do is change your approach, because removing the element from dom has actually nothing to do with an element being draggable
. You need to put encapsulate your draggable with an element for example a div with the same height and width than your draggable, then just destroy the draggable as you please.
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;
}
A jsfiddle example
Upvotes: 8