Mercurial Hosting > dad
view src/dad.js @ 5:1293cb0d30da
minor
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sun, 23 Apr 2023 17:14:52 -0600 |
parents | 0130ae25ef94 |
children | 4d699321068f |
line wrap: on
line source
'use strict'; let dad = {}; { // override these if needed dad.whatToDrag = function(draggable) { return draggable; }; dad.onDrop = function(event) {}; dad.onDropped = function(event) {}; 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); dad.onDrop({ original: original, dragging: dragging, mouseEvent: event, }); original.removeAttribute('dad-original'); dragging.parentNode.removeChild(dragging); document.removeEventListener('mousemove',onMouseMove); document.removeEventListener('mouseup',onMouseUp); document.removeEventListener('mousemove',onMouseMove); document.removeEventListener('touchend',onMouseUp); original.scrollIntoViewIfNeeded(false); let droppedEvent = { original: original, }; original = null; dragging = null; dad.onDropped(droppedEvent); } 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`; original.parentNode.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); }; }