-
Notifications
You must be signed in to change notification settings - Fork 0
/
pollyfill.js
81 lines (67 loc) · 2.42 KB
/
pollyfill.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# pollyfill drag and drop
var drag = () => {
const draggables = document.querySelectorAll('[draggable="true"]');
let offsetX, offsetY;
let isDragging = false;
let currentElement = null;
const addShadow = (element) => {
element.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
};
const removeShadow = (element) => {
element.style.boxShadow = 'none';
};
const dispatchDragEvent = (element, eventType) => {
const event = new CustomEvent(eventType, {
bubbles: true,
cancelable: true,
detail: {
clientX: currentElement ? currentElement.offsetLeft + offsetX : 0,
clientY: currentElement ? currentElement.offsetTop + offsetY : 0
}
});
element.dispatchEvent(event);
};
const onTouchStart = (e) => {
const touch = e.touches[0];
offsetX = touch.clientX - currentElement.offsetLeft;
offsetY = touch.clientY - currentElement.offsetTop;
isDragging = true;
addShadow(currentElement);
dispatchDragEvent(currentElement, 'dragstart');
};
const onTouchMove = (e) => {
if (!isDragging) return;
const touch = e.touches[0];
currentElement.style.left = `${touch.clientX - offsetX}px`;
currentElement.style.top = `${touch.clientY - offsetY}px`;
dispatchDragEvent(currentElement, 'dragover');
};
const onTouchEnd = () => {
isDragging = false;
removeShadow(currentElement);
dispatchDragEvent(currentElement, 'dragend');
currentElement = null;
};
draggables.forEach(element => {
element.addEventListener('touchstart', (e) => {
currentElement = element;
onTouchStart(e);
});
element.addEventListener('touchmove', onTouchMove);
element.addEventListener('touchend', onTouchEnd);
});
document.addEventListener('touchmove', (e) => {
if (isDragging) {
e.preventDefault();
}
});
// Automatically detect and apply the polyfill if necessary
const isTouchDevice = () => {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0;
};
if (isTouchDevice()) {
console.log('Touch device detected. Applying drag-and-drop polyfill.');
// Additional initialization code for the polyfill can go here if needed
}
}
drag()