This class installs global event handlers for dragging and dropping a file or clicking to upload a file. The relevant callback gets called, based on the element that the file was dropped on or selected through. This allows us to swap out and rerender whole sections of the DOM without having to reinstall a bunch of event handlers each time. This nicely decouples the render logic from the drag event management logic.
Also, a class dragging
will be applied to the element when the user drags a
file over it. The name of this class can be changed below if necessary.
- Source:
Example
import ft from "./filetarget.js";
ft.setEventListener("div#file-thing", (file, element) = {
console.log(file); // Will give the name, binary contents, and text contents of the file
console.log(element); // Will give back the div#file-thing element that was clicked/dropped on
}, {
startIn: "documents", // Optional directions for the file picker
types: [{
description: 'My very special file type',
accept: {
'text/plain': ['.extension'],
},
}],
});
```
Methods
(static) setEventListener(selector, handler, options)
Set a global file target listener
Parameters:
Name | Type | Description |
---|---|---|
selector |
string | CSS selector of the element(s) to trigger on |
handler |
fileEventListener | The function to call when a file is uploaded on |
options |
LoadOptions | Options for the file picker |
- Source:
Type Definitions
LoadOptions
Type:
- Object
Properties:
Name | Type | Description |
---|---|---|
types |
Array.<FileTypes> | Which file types are supported |
startIn |
"desktop" | "document" | "downloads" | "music" | "pictures" | "videos" | Where the file picker opens |
- Source:
LoadedFile
Type:
- Object
Properties:
Name | Type | Description |
---|---|---|
name |
string | The name of the file |
binaryContents |
ArrayBuffer | The binary contents of the file |
textContents |
string | The text contents of the file |
- Source:
fileEventListener(file, element)
Handle a global file drop or select event
Parameters:
Name | Type | Description |
---|---|---|
file |
LoadedFile | The file that was uploaded |
element |
HTMLElement | The element that it was uploaded through |
- Source: