Fixed multiple issues that occur when mouseup occurs outside window

This commit is contained in:
simmayor 2018-12-11 23:06:00 -05:00
parent 23b5766b82
commit 2df1812149

View file

@ -1,3 +1,5 @@
let isDragging = false;
document.addEventListener('mousedown', function(event) { document.addEventListener('mousedown', function(event) {
let dragElement = event.target.closest('.draggable'); let dragElement = event.target.closest('.draggable');
@ -5,16 +7,19 @@ document.addEventListener('mousedown', function(event) {
if (!dragElement) return; if (!dragElement) return;
event.preventDefault(); event.preventDefault();
let coords, shiftX, shiftY;
dragElement.ondragstart = function() {
startDrag(event.clientX, event.clientY); return false;
document.addEventListener('mousemove', onMouseMove);
dragElement.onmouseup = function() {
finishDrag();
}; };
let coords, shiftX, shiftY;
startDrag(dragElement, event.clientX, event.clientY);
function onMouseUp(event) {
finishDrag();
};
function onMouseMove(event) { function onMouseMove(event) {
moveAt(event.clientX, event.clientY); moveAt(event.clientX, event.clientY);
} }
@ -22,25 +27,37 @@ document.addEventListener('mousedown', function(event) {
// on drag start: // on drag start:
// remember the initial shift // remember the initial shift
// move the element position:fixed and a direct child of body // move the element position:fixed and a direct child of body
function startDrag(clientX, clientY) { function startDrag(element, clientX, clientY) {
if(isDragging) {
return;
}
isDragging = true;
document.addEventListener('mousemove', onMouseMove);
element.addEventListener('mouseup', onMouseUp);
shiftX = clientX - dragElement.getBoundingClientRect().left; shiftX = clientX - element.getBoundingClientRect().left;
shiftY = clientY - dragElement.getBoundingClientRect().top; shiftY = clientY - element.getBoundingClientRect().top;
dragElement.style.position = 'fixed'; element.style.position = 'fixed';
document.body.append(dragElement);
moveAt(clientX, clientY); moveAt(clientX, clientY);
}; };
// switch to absolute coordinates at the end, to fix the element in the document // switch to absolute coordinates at the end, to fix the element in the document
function finishDrag() { function finishDrag() {
if(!isDragging) {
return;
}
isDragging = false;
dragElement.style.top = parseInt(dragElement.style.top) + pageYOffset + 'px'; dragElement.style.top = parseInt(dragElement.style.top) + pageYOffset + 'px';
dragElement.style.position = 'absolute'; dragElement.style.position = 'absolute';
document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mousemove', onMouseMove);
dragElement.onmouseup = null; dragElement.removeEventListener('mouseup', onMouseUp);
} }
function moveAt(clientX, clientY) { function moveAt(clientX, clientY) {
@ -96,4 +113,4 @@ document.addEventListener('mousedown', function(event) {
dragElement.style.top = newY + 'px'; dragElement.style.top = newY + 'px';
} }
}); });