forked from electricdusk/rushlink
web: Implement drag-and-drop upload
This commit is contained in:
48
assets/js/dragdrop.js
vendored
Normal file
48
assets/js/dragdrop.js
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
|
||||
window.addEventListener('DOMContentLoaded', (event) => {
|
||||
// The implementation of this drag-drop logic is largely based on the
|
||||
// answer described in <https://stackoverflow.com/a/28226022/5207081>.
|
||||
//
|
||||
// The gist is this: every time the drag enters a new DOM object, it will
|
||||
// fire a new 'dragenter' event on that element. That is a pain, because
|
||||
// we do not know which element will be the last to receive a dragleave
|
||||
// event, in case the user aborts the process.
|
||||
//
|
||||
// Therefore, we use an Ugly Hack™. There will be an element with id
|
||||
// 'dropZone', which blocks the complete page. When a 'dragenter' event
|
||||
// is received on any DOM element, we will unhide this modal page-blocker.
|
||||
// This will guarantee us that the next 'enter' event will be received on
|
||||
// this page-block element. This event we shall ignore.
|
||||
//
|
||||
// Then, whenever the user stop their drag action, we will receive the
|
||||
// 'dragleave' on the '#dropZone' element. Now we know when exactly
|
||||
// a drag action is cancelled (and we will hide the modal element
|
||||
// accordingly).
|
||||
|
||||
let dropZone = document.getElementById("dropZone");
|
||||
window.addEventListener("dragenter", (event) => {
|
||||
// User starts a drag action
|
||||
dropZone.style.visibility = "";
|
||||
dropZone.style.opacity = 1;
|
||||
});
|
||||
|
||||
dropZone.addEventListener("drop", (event) => {
|
||||
// User drops a file
|
||||
event.preventDefault();
|
||||
document.getElementById("fileUploadField").files = event.dataTransfer.files;
|
||||
document.getElementById("fileUploadForm").submit();
|
||||
});
|
||||
|
||||
dropZone.addEventListener("dragleave", (event) => {
|
||||
// User cancels drag action
|
||||
dropZone.style.visibility = "hidden";
|
||||
dropZone.style.opacity = 0;
|
||||
});
|
||||
|
||||
window.addEventListener("dragover", (event) => {
|
||||
// Prevent the browser from opening the file, because of a drop event
|
||||
// on the window. (<https://stackoverflow.com/a/6756680/5207081>)
|
||||
event.preventDefault();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user