views:

110

answers:

1

Hi all , Can anyone help me by telling me that in the given code below when the first time element is dragged it works fine but when a new element is dragged then the draggable property of the earlier created element is lost. How can i do the dragging without losing it?

 if(tag==normal_tag1.id)
   {            
      normal_tag_d=' <div id="Normal_Tag1_div_dummy'+count1+'" class ="Normal_Tag1_div_dummy" >'+ 'Normal DUMMY</div>';
      document.getElementById('droppable').innerHTML+=normal_tag_d;
      var idx='#Normal_Tag1_div_dummy'+count1;
        $(idx).draggable(
        {
             revert: 'invalid'
        }
        );
        var droppable="#droppable";
        $(droppable).droppable({
            drop: function(ev,ui) {
            alert(ui.draggable);
            }
        });
      count1++;        
   }
else if(tag==normal_tag2.id)
   { 
      normal_tag2_d=' <div  id="Normal_Tag2_div_dummy'+count2+'" class ="Normal_Tag2_div_dummy" >'+
            'Normal DUMMY2</div>';
      var id='#Normal_Tag2_div_dummy'+count2;
      document.getElementById('droppable').innerHTML+=normal_tag2_d;
      $(id).draggable({
          revert: 'invalid'
      });
      $("#droppable").droppable({
        drop: function() {

        }
        });
      count2++;
   }
A: 

If the draggable is inside the droppable, you're removing it from the DOM when you write over the innerHTML of the droppable. You are simply taking the existing content and adding some more HTML to it, then writing it back to the container. This actually removes the DOM elements inside the container and replaces them with new ones that look exactly like the old ones. Any handlers on the old elements are not reapplied. The other thing I would be concerned about is that you variables aren't scoped to the containing block, but look to be in the global namespace. Of course, you've only included a snippet so I may be misunderstanding the application of the code on both counts.

BTW, you'd be better off (IMO) using jquery for adding the elements as well instead of plain javascript.

if (tag==normal_tag1.id)
{            
      $('<div id="Normal_Tag1_div_dummy'+count1+'" class ="Normal_Tag1_div_dummy" >'+ 'Normal DUMMY</div>')
          .appendTo('#droppable' ) // note this doesn't clear #droppable
          .draggable( {
                revert: 'invalid'
           });
      $('#droppable').droppable({
           drop: function(ev,ui) {
                     alert(ui.draggable);
                 }
      });
}
...
tvanfosson