Drag and Drop: The data being transferred

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 containing file or string
  • type the MIME type of the item

and it has 2 methods:

  • getAsFile() returns a File object representing the data being dragged
  • getAsString() 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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!