This content originally appeared on DEV Community and was authored by Areeb ur Rub
Disclaimer : In this post I am just showing the drag-drop feature, the upload part is totally depends on you that how you want to do it.
You must have seen many sites use drag drop feature to upload files, this feature can be easily implemented by using Javascript event handlers .ondragover
, .ondragleave
and .ondrop
So, fist we need to make a drag-drop-area where files can be dropped. I have used a very general design you can use your creative designs.
drag-drop-area contains what?
The drag drop area should have a <input type="file" hidden>
and a <button>Browse Image</button>
, keep the file-input hidden so that it doesn't interfere in the design and the button will be visible to use the general file select feature.
Designing the drag-drop-area?
There will be 3 design for each event " .ondragover
, .ondragleave
and .ondrop
".
The drag leave will be a simple one which will be the initial design.
The drag over design will be activated when someone drag over the area.
The drop design will be depending on what you are making upload, like here I am uploading images so a preview of image is shown if you are working with documents you can show filenames with default icons.
Each design will be contained in a class and classes will be added and removed on events using java script.
Javascript works
First get all the DOM elements in javascript using
document.querySelector("");
.Then, `let file;' be a variable this will store our file data
Then, create a function which will check button press and file change and will work when someone just use the select file button instead of drag drop
Then create three functions with
.ondragover
,.ondragleave
and.ondrop
and change the classList accordingly, also use preventDefault(); to prevent the page to open the image or file in browser
*The on drop event have a object called dataTransfer
inside this object you can access files to select the first file write event.dataTransfer.files[0];
and equal the file variable to it file = event.dataTransfer.files[0];
*Here, I am creating a showImage()
function you can do what ever you want with the file.
To get a proper Idea see the codepen snippet
You can also read about .ondragover, .ondragleave and .ondrop on MDN docs
Also Read:
Hide NavBar as Scroll down, in less than 10 lines of javascript;
Areeb ur Rub ・ May 24 ・ 1 min read
follow me:
This content originally appeared on DEV Community and was authored by Areeb ur Rub
Areeb ur Rub | Sciencx (2021-05-27T17:02:37+00:00) Drag-Drop-Upload, using JavaScript;. Retrieved from https://www.scien.cx/2021/05/27/drag-drop-upload-using-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.