Skip to content
Advertisement

Drag & drop a file anywhere on a page

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement