Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

JavaScript Resize a Div Layer


Formula and example included.

Pseudo formula:
// Acronyms used to save space.
New style.left = PCW+((E.X-PCX)-(MDX-PCX))
New style.top = PCH+((E.Y-PCY)-(MDY-PCY))

// PCW/PCH = Previous Container Width/Height.
// E.X/E.Y = Event X/Y.
// PCX/PCY = Previous Container Left/Top.
// MDX/MDY = Mouse Down X/Y (where you clicked).

With this formula you will resize the layer relative to where you clicked on it. An extended version of the movement formula. In effect it will take the existing width/height and add the amount of pixel movement as a positive or negative number.

CTRL + click on and hold and drag to resize the layer.


JavaScript
var MouseDownX, MouseDownY, PrevContainerX, PrevContainerY, PrevContainerW, PrevContainerH;
var MouseIsDown = false;
function LayerEvents(e) {
	switch(e.type) {
		case 'mousemove':
			if(e.ctrlKey && MouseIsDown) {
				w = PXValue(document.getElementById('divlayer').style.width);
				h = PXValue(document.getElementById('divlayer').style.height);

				_w = PrevContainerW+((e.clientX-PrevContainerX)-(MouseDownX-PrevContainerX));
				_h = PrevContainerH+((e.clientY-PrevContainerY)-(MouseDownY-PrevContainerY));

				// Minimum size.
				if (_w <= 50 || _h <= 50)
					return;

				document.getElementById('divlayer').style.width = _w +'px';
				document.getElementById('divlayer').style.height =  _h +'px';

			} else if(MouseIsDown) {
				document.getElementById('divlayer').style.left = e.clientX-(MouseDownX-PrevContainerX)+'px';
				document.getElementById('divlayer').style.top = e.clientY-(MouseDownY-PrevContainerY)+'px';
			}
			break;
		case 'mousedown':
			MouseIsDown = true;
			MouseDownX = e.clientX;
			MouseDownY = e.clientY;
			PrevContainerX = PXValue(document.getElementById('divlayer').style.left);
			PrevContainerY = PXValue(document.getElementById('divlayer').style.top);
			PrevContainerW = PXValue(document.getElementById('divlayer').style.width);
			PrevContainerH = PXValue(document.getElementById('divlayer').style.height);
			break;
		case 'mouseup':
			MouseIsDown = false;
	}
}
function PXValue(s) {
	return parseInt(s.replace('px',''));
}



Original Post: Jan 26th, '22 21:01 CET.
Updated: Jan 26th, '22 21:43 CET.

JS
π