Create and size div on click that is draggable and sizable

by johntrepreneur

HTML

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
<title>Create and size div on click that is draggable and sizable</title>
<input type="button" value="Reset"></input><span>Drag in the blue area to create a "shift". Left/right edges of shift are sizable. Shift is draggable.</span>
<div id="resultDiv"></div>

CSS

input {
    width: 100px;
    height: 20px; 
    position: relative; 
    z-index: 10;  
}
span {
    font-size: 10pt;
    margin: 0 0 0 20px;
    position: relative;
    z-index: 10;
}
#resultDiv {
    position: absolute;
    top: 0px;
    bottom: 0px;
    left: 0px;
    right: 0px;
    background-color: lightblue;
    z-index: 0 !important;
}
#resizable {
    width: 1px;
    height: 1px;
    padding: 0.5em;
    background-color: lightgreen;
    border-radius: 10px;
    border: 1px solid green;
}

JavaScript

$(function () {
      $('input').click(function(){
          $('#resizable').remove();
      });
      
      var sizing = false;
      $('#resultDiv').mousedown(function(e){
          
          if ($('#resizable').length > 0)
              return;
          
          // get coordinates
          var offset = $(this).offset();
          var relX = e.pageX - offset.left;
          var relY = e.pageY - offset.top;
                      
          $('<div>').prop('id','resizable').resizable({
              ghost: true,
              handles: 'e, w'
              //,grid: 50,
              //,distance: 100
          })
          .draggable()
          .appendTo('#resultDiv')
          .css({
              'top': relY + 'px',
              'left': relX + 'px'
          });
          sizing = true;
      })
      .mousemove(function(e){
          if (!sizing)
              return;
          var parentOffset = $('#resizable').position();
          $('#resizable').css({
              'height': (e.clientY - parentOffset.top) + 'px',
              'width': (e.clientX - parentOffset.left) + 'px'
          });
      })
      .mouseup(function(e){
          sizing = false;
      });
  });