JQuery make dynamic draggable and droppable containers

The jquery UI javascript has the Draggable and Droppable Interactions inorder to implement a drag drop UI. By default draggable and droppable containers are marked draggable and droppable by jQuery when the page loades, As shown in the code snippet below for the jQuery Drag code and jQuery Drop Code,

jQuery Drop Code using jQuery droppable

$(".dropTarget").droppable({ drop: function(event, ui) { // Drop Logic } });

jQuery Drag Code using jQuery Draggable

$(".drag").draggable({ helper: 'clone', opacity: 0.7, revert: 'invalid' });

If you clone the dragagble or droppable object, via $(this).clone() , the New cloned object that is created is not draggable or droppable. In order to make the new object draggable and droppable, we have to use a plugin called livequery. When you clone an object jQuery doesn't clone its internal events and functions on the new object, which causes the jquery drag code or jquery drop code not to be attached to the new cloned object. When using the livequery plugin, jquery automatically attaches or detaches the drag and drop code to matching selectors. The code after using livequery is as shown below :

jQuery Drop Code with LiveQuery

$(".dropTarget") .livequery(function(){ $(this) .droppable({ drop: function(event, ui) { //Drop Logic Code } }); });

jQuery Drag Code with LiveQuery

$(".drag") .livequery(function(){ $(this) .draggable({ helper: 'clone', opacity: 0.7, revert: 'invalid' }); });

Thus all your current and future objects with class "drag" would be jquery draggable and "dropTarget" would be jquery droppable. clone() or modifiying the DOM via other methods such as innerHTML or createElement and appendChild would make sure that the matching selector elements would have the drag or drop functionality as defined.

Happy Drag Drop Cloning ;)

14 Mar, 2010
Comments (2)
  • Worked for ME

    Thanks! Livequery was what I needed. Wanted to expand what also hung me up to save someone else some trouble:

    $(this).clone(true).appendTo($(this).parent()) = FAILED
    $(this).clone().appendTo($(this).parent()) = SUCCESS

    By Sean on 31 Jul, 2011
  • Excellent

    Was searching for this a long time. Great that you have this here

    By deepak on 14 Jul, 2010
You may also like
On Facebook
Email Newsletter