Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery dynamically created draggable divs

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?

like image 560
man_or_astroman Avatar asked Sep 01 '26 16:09

man_or_astroman


1 Answers

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.

like image 107
gdoron is supporting Monica Avatar answered Sep 04 '26 06:09

gdoron is supporting Monica