views:

54

answers:

3

I am trying to make jquery add new div and then make it draggable but i have been trying and looking on google and i can't find anything here is my code below

 $(document).ready(function() {

 $("#draggable").draggable({ 
   containment: 'parent',
   handle: 'drag_border',
   drag: function(e, ui) {
          var top = ui.position.top;
          var left = ui.position.left;
          $("#top").html(top);
          $("#left").html(left);
           }
       }); 
   });

       function New_Text() {   
            $("<div id=\"draggable\" style=\"width: 200px; height: 50px; border:dashed thin; background-color: #fff\">Drag me</div>").appendTo("div#drag_border"); 
              }

Thank you

A: 

I haven't tried it but this should work:

function New_Text() {   
  $("<div id=\"draggable\" style=\"width: 200px; height: 50px; border:dashed thin; background-color: #fff\">Drag me</div>").appendTo("div#drag_border"); 
        setTimeout(function() {
           ...
          });

         }, 10);
   }

You want to create the div, let the browser add it to the DOM tree, then call the draggable function.

James Black
A: 

The problem here is that you're creating the DIV after you've tried to make it draggable.

jQuery events only work on the elements which exist at the time that the Javascript is run - there are ways around this using the live and delegate functions - but it doesn't look like your plugin allows for that.

So if that code needs to remain the same, move the bit which creates the DIV above the draggable function - and it'll work.

slightlymore
+3  A: 

Create your element, then make it draggable:

$("<div />").draggable();
roosteronacid