comparison 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
comparison
equal deleted inserted replaced
2:264646feb67b 3:6d5e4b38b4fb
1 'use strict';
2
3 let dad = {};
4
5 {
6 // override this if needed
7 dad.whatToDrag = function(draggable) {
8 return draggable;
9 };
10
11
12 let original = null;
13 let dragging = null;
14 let touchX, touchY;
15
16 function onMouseMove(event) {
17 //console.log(event);
18 event.preventDefault();
19 let rect = dragging.getBoundingClientRect();
20 dragging.style.left = `${rect.x+event.movementX}px`;
21 let y = rect.y + event.movementY;
22 if( y < 0 ) {
23 window.scrollBy( 0, y );
24 } else if( y + rect.height > window.innerHeight ) {
25 window.scrollBy( 0, y + rect.height - window.innerHeight );
26 }
27 dragging.style.top = `${y}px`;
28 }
29
30 function onTouchMove(event) {
31 let touches = event.touches;
32 if( touches.length !== 1 )
33 return;
34 let touch = touches[0];
35 let x = touch.clientX;
36 let y = touch.clientY;
37 event.movementX = x - touchX;
38 event.movementY = y - touchY;
39 touchX = x;
40 touchY = y;
41 onMouseMove(event);
42 }
43
44 function onMouseUp(event) {
45 //console.log(event);
46 original.removeAttribute('dad-original');
47 document.body.removeChild(dragging);
48 document.removeEventListener('mousemove',onMouseMove);
49 document.removeEventListener('mouseup',onMouseUp);
50 document.removeEventListener('mousemove',onMouseMove);
51 document.removeEventListener('touchend',onMouseUp);
52 original.scrollIntoViewIfNeeded(false);
53 original = null;
54 dragging = null;
55 }
56
57 function start(event) {
58 //console.log(event);
59 original = dad.whatToDrag(event.target);
60 dragging = original.cloneNode(true);
61 original.setAttribute('dad-original','');
62 dragging.setAttribute('dad-dragging','');
63 let rect = original.getBoundingClientRect();
64 dragging.style.left = `${rect.x}px`;
65 dragging.style.top = `${rect.y}px`;
66 document.body.appendChild(dragging);
67 }
68
69 function onMouseDown(event) {
70 start(event);
71 document.addEventListener('mousemove',onMouseMove);
72 document.addEventListener('mouseup',onMouseUp);
73 }
74
75 function onTouchStart(event) {
76 start(event);
77 let touches = event.touches;
78 if( touches.length !== 1 )
79 return;
80 let touch = touches[0];
81 touchX = touch.clientX;
82 touchY = touch.clientY;
83 document.addEventListener('touchmove',onTouchMove);
84 document.addEventListener('touchend',onMouseUp);
85 }
86
87 dad.setDraggable = function(el) {
88 el.setAttribute('dad-drag','');
89 el.addEventListener('mousedown',onMouseDown);
90 el.addEventListener('touchstart',onTouchStart);
91 };
92 }