JSFiddle - React, Tailwind, and code Playground
by Elmore Cheng
JavaScript
(function () {
const el = document.createElement('div');
const size = 100;
el.style.width = el.style.height = `${size}px`;
el.style.backgroundColor = 'black';
el.style.position = 'absolute';
const offset = { x: 0, y: 0 },
start = { x: 0, y: 0 },
state = { x: 0, y: 0 }
move(start)
if (window.innerWidth <= 640) {
console.log('touch mode');
el.addEventListener('touchstart', event => touchstart(event.touches[0]))
el.addEventListener('touchmove', event => touchmove(event.touches[0]))
el.addEventListener('touchend', event => touchend(event.touches[0]))
} else {
console.log('mouse mode');
el.addEventListener('mousedown', touchstart)
el.addEventListener('mousemove', touchmove)
el.addEventListener('mouseup', touchend)
}
function touchstart(touch) {
offset.x = touch.clientX;
offset.y = touch.clientY;
}
function touchmove(touch) {
state.x = touch.clientX - offset.x + start.x;
state.y = touch.clientY - offset.y + start.y
move(state)
}
function touchend() {
const rect = el.getBoundingClientRect();
start.x = rect.left;
start.y = rect.top;
}
function move({ x, y }) {
el.style.left = `${x}px`;
el.style.top = `${y}px`;
}
document.body.appendChild(el)
})();