Petr Bečka
Petr Bečka

Reputation: 794

dynamically added div is not draggable

I'm trying to make my dynamically added divs draggable but if I call after

$("#draggable").draggable({});

this

for( var i = 0; i < 5; i++ ){
  var smallone = document.createElement('div');
  smallone.id = "draggable";
  smallone.className = "smallDiv";
  smallone.style.bacgroundColor = 'blue';

  document.body.appendChild(smallone);
}

there is no chance to make divs draggable.
I know it works if i create divs first but I need to keep it like this because of my project and this example shows my problem.

Here is fiddle: http://jsfiddle.net/bimbochobot/9jstfwpm/4/

Thank you in advice.

Upvotes: 1

Views: 167

Answers (3)

Divesh Oswal
Divesh Oswal

Reputation: 250

simple 1 ...

for( var i = 0; i < 5; i++ )
{
  var smallone = document.createElement('div');
  smallone.id = "draggable";
  smallone.className = "smallDiv";
  smallone.style.bacgroundColor = 'blue';

  document.body.appendChild(smallone);
  $(".smallDiv").draggable({});
}

it is working... http://jsfiddle.net/9jstfwpm/7/

Upvotes: 0

Muhammad Atif
Muhammad Atif

Reputation: 1102

Use a class instead of id as id must be unique

$(".draggable").draggable({});

Assign draggable class to all divs

Upvotes: 0

Rayon
Rayon

Reputation: 36609

You will have to initialize draggable widget after appending new element.

Try this fiddle:

for( var i = 0; i < 5; i++ )
  {
      var smallone = document.createElement('div');
      smallone.id = "draggable";
      smallone.className = "smallDiv";
      smallone.style.backgroundColor = 'blue';
      document.body.appendChild(smallone);      
      $(smallone).draggable({});
   }

Upvotes: 1

Related Questions