Search code examples
htmldrag-and-dropfileapi

Prevent drag of local code/items from triggering dragenter


Im building an HTML5 file upload, and I want to have the dragenter fire when the user drags a file over the window. The idea is that dragenter will triger a lightbox style overlay, showing the drop zone.

here is my code. (jQuery)

$(window).bind('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#uploadWrapper').show();
}).bind('dragexit', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#uploadWrapper').hide();
});

this works fine, but if the user grabs an image or some texts and drags it, it also trigers, the dragenter event. Is there a way I can tell what is being dragged so only actual files to upload trigger showing the overlay?

Thanks..


Solution

  • I think something like the following should work; (Though I don't think it's Opera friendly.)

    function DraggedFiles(e)
    {
        for (n in e.dataTransfer.types)
        {
            if (e.dataTransfer.types[n] === "Files") return true;
        }
    
        return false;
    }
    

    Then, for your dragEnter event, just add:

    if (DraggedFiles(e))
    {
        // files were dragged onto here
    } else {
        // something other than files were dragged
    }
    

    where you want to make the check and do action/inaction.