David
David

Reputation: 3348

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?

Upvotes: 2

Views: 8097

Answers (3)

David
David

Reputation: 3348

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.

Upvotes: 5

Macsim
Macsim

Reputation: 45

You need to add an event to the entire page in JS (body), that will handle the drop.

Maybe check this article : https://www.smashingmagazine.com/2018/01/drag-drop-file-uploader-vanilla-js/

Upvotes: -2

Aib Syed
Aib Syed

Reputation: 3196

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;
});

Upvotes: 4

Related Questions