Some_Dude
Some_Dude

Reputation: 307

Jquery Resizeable not working for Dynamically created Divs

I am creating divs dynamically and i am setting them to draggable and resizeable. Draggable works just fine, but resizeable does not. I cant figure out why. Here is my code:

function creatediv() {
  var div = document.createElement('div');
  div.className = "draggable resizable";
  div.innerHTML = "You can drag this, but you cannot Resize!! ";
  div.style.position = 'absolute';
  div.style.border = "medium solid black";
  div.style.width = "250px";
  document.getElementById("bdy").appendChild(div);
  $(".draggable").draggable({
    snap: true
  }); //have to call this to activate the jquery draggable effects on the newly created div.
  $(".resizable").resizable();
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<button onclick="creatediv()">Create new element !</button>
<div id="bdy"></div>

Upvotes: 1

Views: 28

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The code works fine, you just haven't included the stylesheet for jQueryUI to make it work:

function creatediv() {
  var div = document.createElement('div');
  div.className = "draggable resizable";
  div.innerHTML = "You can drag this, but you cannot Resize!! ";
  div.style.position = 'absolute';
  div.style.border = "medium solid black";
  div.style.width = "250px";
  document.getElementById("bdy").appendChild(div);
  
  $(".draggable").draggable({
    snap: true
  });
  
  $(".resizable").resizable();
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<!-- Add this \/ -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

<button onclick="creatediv()">Create new element !</button>
<div id="bdy"></div>

It should however be noted that you're using an odd mix of native JS methods and jQuery. If you're going to have the penalty of loading jQuery, it makes sense to make use of its succinct methods. Here's the above logic translated to jQuery:

$('.create').click(function() {
  var $div = $('<div />', {
    'class': 'draggable resizable foo',
    'text': 'You can drag and resize this!'
  }).appendTo('#bdy').draggable({
    snap: true
  }).resizable();
});
.foo {
  position: absolute;
  border: medium solid black;
  width: 250px;
} 
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

<button class="create">Create new element !</button>
<div id="bdy"></div>

Upvotes: 1

Related Questions