comparison src/dad.js @ 4:0130ae25ef94

add drop
author Franklin Schmidt <fschmidt@gmail.com>
date Sat, 22 Apr 2023 21:17:53 -0600
parents 6d5e4b38b4fb
children 1293cb0d30da
comparison
equal deleted inserted replaced
3:6d5e4b38b4fb 4:0130ae25ef94
1 'use strict'; 1 'use strict';
2 2
3 let dad = {}; 3 let dad = {};
4 4
5 { 5 {
6 // override this if needed 6 // override these if needed
7 dad.whatToDrag = function(draggable) { 7 dad.whatToDrag = function(draggable) {
8 return draggable; 8 return draggable;
9 }; 9 };
10 dad.onDrop = function(event) {};
11 dad.onDropped = function(event) {};
10 12
11 13
12 let original = null; 14 let original = null;
13 let dragging = null; 15 let dragging = null;
14 let touchX, touchY; 16 let touchX, touchY;
41 onMouseMove(event); 43 onMouseMove(event);
42 } 44 }
43 45
44 function onMouseUp(event) { 46 function onMouseUp(event) {
45 //console.log(event); 47 //console.log(event);
48 dad.onDrop({
49 draggable: original,
50 dragged: dragging,
51 mouseEvent: event,
52 });
46 original.removeAttribute('dad-original'); 53 original.removeAttribute('dad-original');
47 document.body.removeChild(dragging); 54 dragging.parentNode.removeChild(dragging);
48 document.removeEventListener('mousemove',onMouseMove); 55 document.removeEventListener('mousemove',onMouseMove);
49 document.removeEventListener('mouseup',onMouseUp); 56 document.removeEventListener('mouseup',onMouseUp);
50 document.removeEventListener('mousemove',onMouseMove); 57 document.removeEventListener('mousemove',onMouseMove);
51 document.removeEventListener('touchend',onMouseUp); 58 document.removeEventListener('touchend',onMouseUp);
52 original.scrollIntoViewIfNeeded(false); 59 original.scrollIntoViewIfNeeded(false);
60 let droppedEvent = {
61 draggable: original,
62 };
53 original = null; 63 original = null;
54 dragging = null; 64 dragging = null;
65 dad.onDropped(droppedEvent);
55 } 66 }
56 67
57 function start(event) { 68 function start(event) {
58 //console.log(event); 69 //console.log(event);
59 original = dad.whatToDrag(event.target); 70 original = dad.whatToDrag(event.target);
61 original.setAttribute('dad-original',''); 72 original.setAttribute('dad-original','');
62 dragging.setAttribute('dad-dragging',''); 73 dragging.setAttribute('dad-dragging','');
63 let rect = original.getBoundingClientRect(); 74 let rect = original.getBoundingClientRect();
64 dragging.style.left = `${rect.x}px`; 75 dragging.style.left = `${rect.x}px`;
65 dragging.style.top = `${rect.y}px`; 76 dragging.style.top = `${rect.y}px`;
66 document.body.appendChild(dragging); 77 original.parentNode.appendChild(dragging);
67 } 78 }
68 79
69 function onMouseDown(event) { 80 function onMouseDown(event) {
70 start(event); 81 start(event);
71 document.addEventListener('mousemove',onMouseMove); 82 document.addEventListener('mousemove',onMouseMove);