Making An Element Resizeable and Draggable

The drag and dragStart events can be used to make an element resizeable by dragging.

Quick & Easy

I've provided very simple event listeners just for this purpose. These listeners implement basic resizing and basic dragging. If you need more functionality than what these simple listeners provide, then I'll discuss how to write your own below. The following is all the javascript for the example on this page.

var e1;
function windowOnload() {
  with (e1 = document.getElementById('e1').cbe) {
    color('#ff3333');
    background('#ccccff');
    resizeTo(125,125);
    moveTo('e',10);
    show();
    addEventListener('dragResize'); // now e1 is draggable and resizeable 
  }  
}

Top

Writing Your Own Resize Event Listener

I'll show how I wrote my dragResize listeners, and that should get you started writing your own. The following is what I wrote before I incorporated this feature into CBE.

The windowOnload() Function

The windowOnload function initializes the element and adds drag and dragStart event listeners.

var e1;
function windowOnload() {
  with (e1 = document.getElementById('e1').cbe) {
    background('#ccccff');
    resizeTo(125,125);
    moveTo('e',10);
    show();
    addEventListener('dragStart', dragStartListener);
    addEventListener('drag', dragListener);
  }  
}

The dragStartListener() Function

The dragStartListener checks if the initial mouseDown event occured in the resize corner of the element. In this case, I'm using a 20 by 20 area in the bottom-right corner. If this was true, then the isResizing property is set to true, else false.

function dragStartListener(e) {
  if (
    e.offsetX > (e.cbeCurrentTarget.width() - 20)
    &&
    e.offsetY > (e.cbeCurrentTarget.height() - 20)
  ) {
    e.cbeCurrentTarget.isResizing = true;
  }
  else e.cbeCurrentTarget.isResizing = false;
}

The dragListener() Function

The dragListener either drags or resizes the element, depending on the value of the isResizing property.

function dragListener(e) {
  if (e.cbeCurrentTarget.isResizing) e.cbeCurrentTarget.resizeBy(e.dx, e.dy);
  else e.cbeCurrentTarget.moveBy(e.dx, e.dy);
}
e1

draggable

resizeable