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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

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