Jquery dynamically created draggable divs

man_or_astroman picture man_or_astroman · Apr 25, 2012 · Viewed 8.2k times · Source

In my project im creating dynamically divs with jquery everytime you click a button. Now i want these new divs to have draggable and resizable properties. Here is what ive done so far:

$("#button1").click(function(){
     $("<div/>", {
       "id": "test",
        text: "",
      }).appendTo("body");
     $( "#test" ).resizable();
     $( "#test" ).draggable();
  });

This code works somehow, the problem is that only the first div that was created is resizable and draggable. Also is it possible to put another button in order to delete these new created divs?

Answer

gdoron is supporting Monica picture gdoron is supporting Monica · Apr 25, 2012

id must be unique! you create multiple divs with the same test id => INVALID HTML

Another thing, you don't need to query the DOM, you can use the reference you got to make the created <div> resizable and draggable:

$("#button1").click(function(){
     $("<div/>", {
       "class": "test",
        text: "",
      }).resizable().draggable()
      .appendTo("body");
  });

If you want to use id for some reason:

var counter = 1;

$("#button1").click(function(){
     $("<div/>", {
       "class": "test" + (counter++),
        text: "",
      }).resizable().draggable()
      .appendTo("body");
  });

#id selector comment in the docs site:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.