Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQueryUI: properly removing a draggable element

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?

like image 509
Daniel Buckmaster Avatar asked Jul 12 '12 13:07

Daniel Buckmaster


1 Answers

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

like image 190
KoU_warch Avatar answered Sep 23 '22 11:09

KoU_warch