Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 27, 2021 05:02 pm GMT

Drag-Drop-Upload, using JavaScript;

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:

follow me:

.ltag__user__id__417828 .follow-action-button { background-color: #000000 !important; color: #ffffff !important; border-color: #000000 !important; }
areeburrub image

Original Link: https://dev.to/areeburrub/drag-drop-upload-using-javascript-29n9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To