Native JavaScript Drag&Drop Upload

Ciprian on Friday, July 13, 2018 in JavaScript DOM

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Modern browsers allow you to define native dragging & dropping functionality with a graceful degradation for older/ancient browsers, such as Internet Explorer, Edge and Safari.

Here’s my take on a simple drag & drop uploader.
Codepen demo.

Here’s the HTML code:

<div id="dropContainer" class="dropSelector">
    <b>Drop files here</b>
    <br>or
    <br>
    <input type="file" id="fileInput">
</div>

Here’s the CSS code:

body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Segoe UI Symbol", "Segoe UI Emoji", "Apple Color Emoji";
    font-size: 14px;
    line-height: 1.5;
    color: #24292e;
    background-color: #fff;
}

#dropContainer {
    border: 4px dashed #CCCCCC;
    border-radius: 8px;
    height: 200px;
    color: #CCCCCC;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
#dropContainer b {
    font-size: 24px;
    font-weight: 400;
}
#fileInput {
    width: auto;
    margin: 24px 0 0 0;
    padding: 8px;
    font-family: inherit;
    font-size: inherit;
    box-shadow: 0 0 16px rgba(0, 0, 0, 0.1);
}

And here’s the JavaScript code:

window.onload = function() {
    document.getElementById("dropContainer").ondragover = document.getElementById("dropContainer").ondragenter = function (evt) {
        evt.preventDefault();
    };

    document.getElementById("dropContainer").ondrop = function (evt) {
        document.getElementById("fileInput").files = evt.dataTransfer.files;
        evt.preventDefault();
    };
};

Keep it simple and enjoy!

Related posts

Leave a Reply

You have to agree to the comment policy.