diff src/dad.js @ 3:6d5e4b38b4fb

start drag
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 21 Apr 2023 00:58:31 -0600
parents
children 0130ae25ef94
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/dad.js	Fri Apr 21 00:58:31 2023 -0600
@@ -0,0 +1,92 @@
+'use strict';
+
+let dad = {};
+
+{
+	// override this if needed
+	dad.whatToDrag = function(draggable) {
+		return draggable;
+	};
+
+
+	let original = null;
+	let dragging = null;
+	let touchX, touchY;
+
+	function onMouseMove(event) {
+		//console.log(event);
+		event.preventDefault();
+		let rect = dragging.getBoundingClientRect();
+		dragging.style.left = `${rect.x+event.movementX}px`;
+		let y = rect.y + event.movementY;
+		if( y < 0 ) {
+			window.scrollBy( 0, y );
+		} else if( y + rect.height > window.innerHeight ) {
+			window.scrollBy( 0, y + rect.height - window.innerHeight );
+		}
+		dragging.style.top = `${y}px`;
+	}
+
+	function onTouchMove(event) {
+		let touches = event.touches;
+		if( touches.length !== 1 )
+			return;
+		let touch = touches[0];
+		let x = touch.clientX;
+		let y = touch.clientY;
+		event.movementX = x - touchX;
+		event.movementY = y - touchY;
+		touchX = x;
+		touchY = y;
+		onMouseMove(event);
+	}
+
+	function onMouseUp(event) {
+		//console.log(event);
+		original.removeAttribute('dad-original');
+		document.body.removeChild(dragging);
+		document.removeEventListener('mousemove',onMouseMove);
+		document.removeEventListener('mouseup',onMouseUp);
+		document.removeEventListener('mousemove',onMouseMove);
+		document.removeEventListener('touchend',onMouseUp);
+		original.scrollIntoViewIfNeeded(false);
+		original = null;
+		dragging = null;
+	}
+
+	function start(event) {
+		//console.log(event);
+		original = dad.whatToDrag(event.target);
+		dragging = original.cloneNode(true);
+		original.setAttribute('dad-original','');
+		dragging.setAttribute('dad-dragging','');
+		let rect = original.getBoundingClientRect();
+		dragging.style.left = `${rect.x}px`;
+		dragging.style.top = `${rect.y}px`;
+		document.body.appendChild(dragging);
+	}
+
+	function onMouseDown(event) {
+		start(event);
+		document.addEventListener('mousemove',onMouseMove);
+		document.addEventListener('mouseup',onMouseUp);
+	}
+
+	function onTouchStart(event) {
+		start(event);
+		let touches = event.touches;
+		if( touches.length !== 1 )
+			return;
+		let touch = touches[0];
+		touchX = touch.clientX;
+		touchY = touch.clientY;
+		document.addEventListener('touchmove',onTouchMove);
+		document.addEventListener('touchend',onMouseUp);
+	}
+
+	dad.setDraggable = function(el) {
+		el.setAttribute('dad-drag','');
+		el.addEventListener('mousedown',onMouseDown);
+		el.addEventListener('touchstart',onTouchStart);
+	};
+}