drag and draw a rectangle div

drag and draw a rectangle (or a div with a border) - see discussion at https://stackoverflow.com/questions/8884803/jquery-drag-and-draw

by Andy Bulka

HTML

<div id="container">Draw selection here</div>

CSS

body {
    font-family: sans-serif;
  }

  #container {
    width: 400px;
    height: 300px;
    background: #ddd;
    line-height: 300px;
    text-align: center;
    color: #666;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
  }

  .selection-box {
    position: absolute;
    background: transparent;
    border: 1px dotted #000;
  }

JavaScript

$(function () {
  var $container = $('#container');
  var $selection = $('<div>').addClass('selection-box');
  var click_y, click_x

  function box(e) {
    var move_x = e.pageX,
        move_y = e.pageY,
        width = Math.abs(move_x - click_x),
        height = Math.abs(move_y - click_y),
        new_x, new_y;

    new_x = (move_x < click_x) ? (click_x - width) : click_x;
    new_y = (move_y < click_y) ? (click_y - height) : click_y;

    let result = {
      'width': width,
      'height': height,
      'top': new_y,
      'left': new_x
    }
    return result
  }

  function on_mousedown(e) {
    click_y = e.pageY
    click_x = e.pageX
    $selection.css({
      'top': click_y,
      'left': click_x,
      'width': 0,
      'height': 0
    });
    $selection.appendTo($container);
    //console.log("created selection box")
    $container.on('mousemove', mmove)
    $container.on('mouseup', mup)
  }
  function mmove(e) {
    let b = box(e)
    //console.log("mousemove box", b)
    $selection.css(b)
  }
  function mup(e) {
    // $container.off('mousemove');
    $container.unbind('mousemove', mmove);
    $container.unbind('mouseup', mup);
    $selection.remove();
    console.log("mouseup", box(e))
  }
  $container.on('mousedown', on_mousedown );
});