I have the following code:
<input type="file" name="file" id="file">
You can click on it to select a file. But alternatively you can drag a file and drop it on the Select file button. But you have to exactly hold the cursor above the button when dropping the file. Otherwise it won't work.
There are ways to make the button or the drop zone bigger.
But I'd like to make the entire page a drop zone. So I can drop the file anywhere on the entire page and still id="file" will „receive“ it.
I just need the functionality itself. I don't need a hover animation or something like this.
How is it possible?
I finally ended up with this fully working code:
<script>
document.addEventListener('dragover', (e) => {
e.preventDefault()
});
document.addEventListener('drop', (e) => {
document.getElementById('file').files = e.dataTransfer.files;
e.preventDefault()
});
</script>
<input type="file" name="file" id="file">
Additionally, I added document.getElementById('file').onchange(); to the drop event listener because there's an onchange in my input that wouldn't get called this way.
To make the entire page a drop zone, you can add an event listener to the body element and define the event handler function.
This function will be called when a file is dropped onto the page. You can then use the target element from the event object to access the file input element and set the file accordingly.
Example:
const dropZone = document.querySelector('body');
dropZone.addEventListener('drop', (e) => {
const fileInput = document.getElementById('file');
fileInput.files = e.dataTransfer.files;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With