You can access the items being transferred from the dataTransfer.items
property, which is an array-like object which you can iterate using a loop and get access to each DataTransferItem
object.
DataTransferItem
has 2 read-only properties:
kind
: the kind of the item being dragged. Returns a string containingfile
orstring
type
the MIME type of the item
and it has 2 methods:
getAsFile()
returns aFile
object representing the data being draggedgetAsString()
executes the callback function pasing a string object representing the data being dragged
They have a similar name but work very differently. The first returns a File
object:
element.addEventListener('dragenter', event => {
for (item of event.dataTrasfer.items) {
const theFile = item.getAsFile()
}
})
Learn more about File objects at https://flaviocopes.com/file/
The second passes the item as a string to a callback function:
element.addEventListener('dragenter', event => {
for (item of event.dataTrasfer.items) {
item.getAsString(theString => {
console.log(theString)
})
}
})
The types of items files being dragged is stored in the types
property of the dataTransfer
object. It is an array containing the string string
by default. If we are dragging a file, the corresponding type is a string of value Files
.
If there are files being transferred, in addition to being listed in dataTransfer.items
, they are stored in the files
property of dataTransfer
.
This property points to a FileList
object listing the files being dragged.
Lessons in this unit:
0: | Introduction |
1: | Drop targets |
2: | Drag events |
3: | Dragging data |
4: | Set / get the effect |
5: | ▶︎ The data being transferred |