jQuery UI resizable function not working on dynamic div

时间:2017-05-16 09:16:43

标签: javascript jquery html css jquery-ui

Resizable function in jquery ui is not working with dynamic div instead when I make the static ( means copy and page the div code in HTML ) it start working. Why?

$(function(){
  $("#textTemplate").draggable({
    zIndex: 2500,
    helper: 'clone',
  });

  $("#editorDesignView").droppable({
    accept: '#textTemplate',
    drop: function(event, ui) {
      var html = '<div id="" class="resize" style="background: #eee; width: 80%; margin: 10px auto; padding: 10px;"><p contenteditable="true" style="padding: 5px;" onclick="$(this).focus();">Add your text here.</p></div>';
      $(html).appendTo(this).hide().slideDown();
      var currentHtml = $("#editor").val();       
      $("#editor").val(currentHtml+html);
    }
  });

  $('#editorDesignView').sortable();

  $('#editorBlock div#editorDesignView div#sortable_elements').resizable();
});

2 个答案:

答案 0 :(得分:1)

You should initialize resize function after drop has finished for dynamically created div as follows:

$(function(){
  $("#textTemplate").draggable({
    zIndex: 2500,
        helper: 'clone',
  });
  $( "#editorDesignView" ).droppable({
    accept: '#textTemplate',
      drop: function( event, ui ) {
        var html = '<div id="" class="resize" style="background: #eee; width: 80%; margin: 10px auto; padding: 10px;"><p contenteditable="true" style="padding: 5px;" onclick="$(this).focus();">Add your text here.</p></div>';
  $(html).appendTo(this).hide().slideDown();
  var currentHtml = $("#editor").val();       
  $("#editor").val(currentHtml+html);
  $('#editorDesignView').sortable();
  $( '#editorBlock div#editorDesignView div.resize' ).resizable();
      }
    });
});

Code Pen

答案 1 :(得分:0)

Those divs in static HTML are activated with resizable property by
('#editorBlock div#editorDesignView div#sortable_elements').resizable();
right after the page is successfully loaded.

Then after a while you create some new divs, but these new divs will never been activated with resizable property.

You need to reactivate newly created div at the end of
$("#editorDesignView").droppable({...})
by adding .sortable() .resizeble()
under the line $("#editor").val(currentHtml+html); (just in this case)