Search code examples
jqueryliveresizable

Jquery Resizable problem after class is added with live()


resizable() no longer works when the created div is clicked. All i'm doing is adding a class with live(). What is the solution to this problem.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/base/jquery-ui.css" type="text/css" media="all" /> 
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js" type="text/javascript"></script> 

<style>
    .aaa { width:100px; height:100px;background-color:#ccc;margin-bottom:5px;}
    p{widht:500px; height:500px; margin:0px; padding:0px;border:2px solid red;color:#000;}
</style>


<button>Click to create divs</button>
<p id="ptest"></p>

<script type="text/javascript">
var dividcount = 1;

$("button").click(function() {
    var myDiv = $('<div id=lar' + dividcount + ' class=aaa></div>');
    $(myDiv).resizable().draggable().appendTo('#ptest');

    dividcount++;
});

$('div').live('click', function() {

    $('div').removeClass('selected');
    $('div').html('');

    $(this).addClass('selected');
    $(this).html('div #' + this.id);
});
</script>

Solution

  • It's because of this:

    $('div').html('');
    

    You clear out the HTML inside the div. When you make something resizable, jQuery UI adds some content that it needs. For example:

    <div id="lar1" class="aaa ui-resizable ui-draggable" style="position: absolute; top: 38px; left: 12px; width: 125px; height: 120px; ">
      <div class="ui-resizable-handle ui-resizable-e"></div>
      <div class="ui-resizable-handle ui-resizable-s"></div>
      <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 1001; "></div>
    </div>
    

    One way to address this issue is to put your text in a specific container and modify that, e.g.:

        $('div').live('click', function() {
    
            $('div').removeClass('selected');
            $('div .my-text').remove();
    
            $(this).addClass('selected');
            $('<div class="my-text">div #' + this.id + '</div>').appendTo($(this));
        });