Native JavaScript Drag&Drop Upload

πŸ‘‹ Ciprian on Friday, July 13, 2018 in Blog, JavaScript
Last modified on Friday, July 13, 2018

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: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
        -ms-flex-direction: column;
            flex-direction: column;
    -webkit-box-pack: center;
        -ms-flex-pack: center;
            justify-content: center;
    -webkit-box-align: center;
        -ms-flex-align: 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;
    -webkit-box-shadow: 0 0 16px rgba(0, 0, 0, 0.1);
            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!

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

πŸ‘‹ Added by Ciprian on Friday, July 13, 2018 in Blog, JavaScript. Last modified on Friday, July 13, 2018.

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy