2

I am trying to create div which are draggable as well as resizable. Now, if I hardcode one div at design time, it works. However, if I add divs at run time, draggable does not work.

/*----------------------*/

. movingDiv { 
    border: 1px solid;
    width: 150px; 
    height: 150px; 
    padding: 0.5em; 
    resize: both;
    overflow: auto;
    position: absolute;
}
/*-----------------*/

.........
.........
 <div id="source">
</div>
<div id="container">    
<div class="movingDiv">
    <p>Drag and resize</p>
</div>
</div>
</body>

<script>
  $("#source").click(function () {
      $("#container").append('<div class="movingDiv"></div>');
    });

  $(".movingDiv").resizable().draggable();
</script>
jine
  • 99
  • 2
  • 7
  • When you call `.resizable()` and `.draggable()` it only applies to items that exist at that time. You need to use event delegates. See link above – freedomn-m Nov 13 '16 at 01:30

2 Answers2

0

You should make it:

$("#container").append('<div class="movingDiv"></div>').draggable().resizable();

This way draggable() and resizable() are called on each new div when its created not just once at the beginning of execution.

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
nshoo
  • 939
  • 8
  • 17
0

And here is a working example of what @TimTheEnchanter already proposed:

$("#source").click(function () {
  $("#container").append($('<div class="movingDiv"><p>Drag and resize</p</div>').draggable().resizable());
});
.movingDiv { 
    border: 1px solid;
    width: 150px; 
    height: 150px; 
    padding: 0.5em; 
    overflow: hidden;
    position: absolute;
}
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="source">source</div>
<div id="container">    

</div>
Flyer53
  • 754
  • 6
  • 14