getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

Native JavaScript Drag&Drop Upload

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.

Added by Ciprian on Friday, July 13, 2018 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy