One way to make the entire page a drop zone for drag and drop is to toggle its visibility based on dragenter
, dragleave
and drop
events.
First, in the html:
<div class="drop-zone" style="visibility: hidden; opacity: 0"></div>
in CSS:
.drop-zone {
/* From top left to cover entire window */
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* Z-index to cover everything else */
z-index: 9999999999;
/* dim the page with 20% black background when visible */
background-color: rgba(0, 0, 0, 0.2);
transition: visibility 175ms, opacity 175ms;
}
In Javascript:
// Global variable to track which element is being dragged inside of
let lastTarget;
// When dragging into the window, make the drop zone visible
window.addEventListener("dragenter", function (e) {
lastTarget = e.target;
document.querySelector(".drop-zone").style.visibility = "";
document.querySelector(".drop-zone").style.opacity = 1;
});
// When leaving, hide drop zone
window.addEventListener("dragleave", function (e) {
if (e.target === lastTarget || e.target === document) {
document.querySelector("#drop-zone").style.visibility = "hidden";
document.querySelector("#drop-zone").style.opacity = 0;
}
});
// Also hide when dropped
addEventHandler(drop, "drop", function (e) {
// Handle your usual drop actions
// and then hide
if (e.target === lastTarget || e.target === document) {
document.querySelector("#drop-zone").style.visibility = "hidden";
document.querySelector("#drop-zone").style.opacity = 0;
}
});