Grow your CSS skills. Land your dream job.

Last updated on:

Test if dragenter/dragover Event Contains Files

HTML5 drag and drop is great for handling file uploads. But if that's the only thing you are using it for, it's nice to know if any particular dragenter or dragover event actually has files. Unlike, for example, just the dragging of some selected text.

Send the event object to this function and it will return the truth (assuming you are in a browser that supports all this):

function containsFiles(event) {

    if (event.dataTransfer.types) {
        for (var i = 0; i < event.dataTransfer.types.length; i++) {
            if (event.dataTransfer.types[i] == "Files") {
                return true;
            }
        }
    }
    
    return false;

}

Reference URL

Comments

  1. dgriesel
    Permalink to comment#

    How about this?

    if ( t = event.dataTransfer.types )
        return t.contains("Files")
    
    • tbruun
      Permalink to comment#

      Beware that types in Firefox is a DOMStringList, while in Chrome it’s an Array. You can use types.indexOf("Files") !== -1, but that won’t work with the DOMStringList. At this point you might as well go with the author’s solution.

  2. Jeff Ayer
    Permalink to comment#

    A different ie9+ take:

    containsFiles = function(e) {
        var dataType = Array.prototype.slice.call(e.dataTransfer.types);
    
        dataType = dataType.filter(function(e) {
            return e == "Files";
        });
    
        return dataType.length;
    }
    

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".