Having a drag and drop zone for file uploads is a very common thing these days, and it’s very user friendly. So, Let’s create a drag & drop zone for input file element without any external libraries. But it will work on modern browsers only.

First, we create the markup for the drop zone area using a div element with an input file element inside of it.

<div class="dropzone" id="dropzone">
	<img class="dropzone-icon" src="https://wickedev.com/wp-content/uploads/2021/02/cloud-uploading.png" />
    
	Drop files or Click here to select files to upload.
	<input type="file" name="files" class="dropzone-input" multiple />
</div>

 

Its time to add some styles to make it look like a drop zone area. We also hide the input file element, because we do not want the users to see the input field.

.dropzone {
	border: 0.2rem dashed #6583fe;
	padding: 2rem;
	border-radius: 0.25rem;
	background-color: #fff;
	text-align: center;
	font-size: 1.5rem;
	transition: 0.25s background-color ease-in-out;
	cursor: pointer;
}

.dropzone-dragging,
.dropzone:hover {
	background-color: #f3f5ff;
}

.dropzone-icon {
	max-width: 75px;
	display: block;
	margin: 0 auto 1.5rem;
}

.dropzone-input {
	display: none;
}

 

Now that we’ve our markup and styles are ready, we add the javascript to make our drop zone functional.

var dropzone = document.getElementById('dropzone');
var dropzone_input = dropzone.querySelector('.dropzone-input');
var multiple = dropzone_input.getAttribute('multiple') ? true : false;

['drag', 'dragstart', 'dragend', 'dragover', 'dragenter', 'dragleave', 'drop'].forEach(function(event) {
    dropzone.addEventListener(event, function(e) {
        e.preventDefault();
        e.stopPropagation();
    });
});

dropzone.addEventListener('dragover', function(e) {
    this.classList.add('dropzone-dragging');
}, false);

dropzone.addEventListener('dragleave', function(e) {
    this.classList.remove('dropzone-dragging');
}, false);

dropzone.addEventListener('drop', function(e) {
    this.classList.remove('dropzone-dragging');
    var files = e.dataTransfer.files;
    var dataTransfer = new DataTransfer();

    Array.prototype.forEach.call(files, file => {
        dataTransfer.items.add(file);
        if (!multiple) {
            return false;
        }
    });

    var filesToBeAdded = dataTransfer.files;
    dropzone_input.files = filesToBeAdded;
}, false);

dropzone.addEventListener('click', function(e) {
    dropzone_input.click();
}, false);

 

Now, you can put it inside any form element and write server side codes to handle the uploads. 🙂

You can see it in action here:

See the Pen
PobNNwE
by Zahed Kamal (@zahedkamal87)
on CodePen.

 

There are so many popular drag and drop file uploader libraries, eg – DropzoneJS, jQuery File Upload. But, If you are looking for a tiny script to create a drop zone, then try DnD Zone.