Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

JavaScript Moving a Div Layer


Formula and example included.

Pseudo formula:
New style.left = MovingMouseX-(PushedMouseX-PreviousStyleLeft)
New style.top = MovingMouseY-(PushedMouseY-PreviousStyleTop)

With this formula you will move the layer relative to where you clicked on it.

Click on and hold, to move this layer.

JavaScript
var MouseDownX, MouseDownY, PrevContainerX, PrevContainerY;
var MouseIsDown = false;
function LayerEvents(e) {
	switch(e.type) {
		case 'mousemove':
			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);
			break;
		case 'mouseup':
			MouseIsDown = false;
	}
}
function PXValue(s) {
	return parseInt(s.replace('px',''));
}



Original Post: Jan 26th, '22 20:57 CET.
Updated: Jan 26th, '22 21:07 CET.

JS
π