Jquery dynamically created draggable divs

In my project, I create dynamically divs with jquery every time you click a button. Now I want these new divs to have drag and drop properties. Here is what I have 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 created was resized and dragged. You can also put another button to delete these newly created divs?

+3
source share
2 answers

idmust be unique! you create multiple divs with the same testid => INVALID HTML

, DOM, , , <div> resizable draggable:

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

id - :

var counter = 1;

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

#id docs:

id . , , , DOM. ; , , .

+5

.

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

All Articles