Home > Mobile >  Drag & drop a file anywhere on a page
Drag & drop a file anywhere on a page

Time:12-05

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?

CodePudding user response:

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

CodePudding user response:

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/

  • Related