Friday, June 5, 2009

Element Relocation with jQuery Drag and Drop

I got stuck the other day trying to figure out how to do something pretty simple. I was trying to use jQuery’s Drag and Drop to move an element between to Drop containers. It seemed that whenever I dropped the element into the container it would automagically disappear. I played around with cloning (http://docs.jquery.com/Clone), searched the web like crazy and generally kept hitting the make it work button over and over again. Using Firebug I was able to see that indeed the element was transferred to the new box. So I got a second pair of eyes on it which somehow allowed me to be distracted enough to notice that their was a brand new scroll bar at the bottom of the screen and the element was hidden off to the right. Somehow the location was messed up.

I fixed it by adding the following to the drop function $(ui.draggable).attr("style", "");

Here is the complete script for the Drop container:


<div id="goodDrop" class="cart" style="clear:left; height:132px;margin-top:10px;">
<script type="text/javascript">
//<![CDATA[
$("#goodDrop").droppable({ accept: '.draggableFacet', hoverclass:'cart-active',
    drop:function(event, ui){
     $(this).append( $(ui.draggable) );
     $(ui.draggable).attr("style", "");
    }
   });

//]]>
</script>
</div>



The complete code can be found here and a working example here. One problem I am still bangin my head on is that once a drop is performed the element can still be dragged but you don't see it move until you drop it in a new droppable.

1 comment:

  1. Thanks for the info, I need this for a project I'm working on. After writing this, have you had any luck figuring out why it stops visually dragging after it's been dropped?

    ReplyDelete