Transfer multiple files by dragging and dropping them into a single file upload option

I was experimenting with adding a drag and drop feature to my website. After trying several scripts, I came across one on CodePen. However, the script allows for the upload of multiple files, while I only need to upload a single PDF or .doc file. Can someone help me understand how to modify it to suit my needs?

    "use strict";

//DOM
var $ = document.querySelector.bind(document);

//APP
var App = {};
App.init = function () {
    // Initialization
    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // File template
        var template = "" + Object.keys(files).map(function (file) {
            return "<div class=\"file file--" + file + "\">\n     <div class=\"name\"><span>" + files[file].name + "</span></div>\n     <div class=\"progress active\"></div>\n     <div class=\"done\">\n\t<a href=\"\" target=\"_blank\">\n      <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" x=\"0px\" y=\"0px\" viewBox=\"0 0 1000 1000\">\n\t\t<g><path id=\"path\" d=\"M500,10C229.4,10,10,229.4,10,500c0,270.6,219.4,490,490,490c270.6,0,490-219.4,490-490C990,229.4,770.6,10,500,10z M500,967.7C241.7,967.7,32.3,758.3,32.3,500C32.3,241.7,241.7,32.3,500,32.3c258.3,0,467.7,209.4,467.7,467.7C967.7,758.3,758.3,967.7,500,967.7z M748.4,325L448,623.1L301.6,477.9c-4.4-4.3-11.4-4.3-15.8,0c-4.4,4.3-4.4,11.3,0,15.6l151.2,150c0.5,1.3,1.4,2.6,2.5,3.7c4.4,4.3,11.4,4.3,15.8,0l308.9-306.5c4.4-4.3,4.4-11.3,0-15.6C759.8,320.7,752.7,320.7,748.4,325z\"</g>\n\t\t</svg>\n\t\t\t\t\t\t</a>\n     </div>\n    </div>";
        }).join("");

        $("#drop").classList.add("hidden");
        $("footer").classList.add("hasFiles");
        $(".importar").classList.add("active");
        setTimeout(function () {
            $(".list-files").innerHTML = template;
        }, 1000);

        Object.keys(files).forEach(function (file) {
            // Simulated progress delay
            var load = 2000 + file * 2000; 
            setTimeout(function () {
                $(".file--" + file).querySelector(".progress").classList.remove("active");
                $(".file--" + file).querySelector(".done").classList.add("anim");
            }, load);
        });
    }

    // Trigger file input
    $("#triggerFile").addEventListener("click", function (evt) {
        evt.preventDefault();
        $("input[type=file]").click();
    });

    // Drop events
    $("#drop").ondragleave = function (evt) {
        $("#drop").classList.remove("active");
        evt.preventDefault();
    };
    $("#drop").ondragover = $("#drop").ondragenter = function (evt) {
        $("#drop").classList.add("active");
        evt.preventDefault();
    };
    $("#drop").ondrop = function (evt) {
        $("input[type=file]").files = evt.dataTransfer.files;
        $("footer").classList.add("hasFiles");
        $("#drop").classList.remove("active");
        evt.preventDefault();
    };

    // Upload more files
    $(".importar").addEventListener("click", function () {
        $(".list-files").innerHTML = "";
        $("footer").classList.remove("hasFiles");
        $(".importar").classList.remove("active");
        setTimeout(function () {
            $("#drop").classList.remove("hidden");
        }, 500);
    });

    // Input change event
    $("input[type=file]").addEventListener("change", handleFileSelect);
}();

Link to CodePen : https://codepen.io/jotavejv/pen/bRdaVJ

Thank you in advance :)

Answer №1

When working with source code on CodePen that involves using the "multiple" attribute, it's important to note that if you only want to upload one file at a time, you should consider removing the "multiple" attribute.

For example:

<input type="file" multiple="multiple" />

In this case, you would need to change it to:

<input type="file" />

I hope this solution helps address your issue!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for activating a function during a click on the download button within an audio tag in HTML

Is there a way to track the number of downloads when using an audio tag with a download option? Which event handler should I use for this task and how can I implement it? I have already set up a fully functional back end API, but I am struggling to unders ...

What is the best method for sending a PHP variable to an AJAX request?

I am working with three files - my main PHP file, functions.php, and my JS file. My challenge is to pass a PHP variable to JavaScript. Below is a snippet from my MAIN PHP FILE: function ccss_show_tag_recipes() { //PHP code here } Next, here's t ...

Is there a way to retrieve an HTML file from a different directory using Express?

I am currently utilizing an HTML file in the same folder. How can I access an HTML file saved in a different folder using express? Thank you. const express=require('express') const path=require('path') const app=express() app.get(& ...

"Why is it that only one of the two similar spans with onclick event is not functioning properly

Encountering a perplexing issue that has me stumped. Here's the code in question: js: function Test() { alert("test"); } html: <span id='bla' onclick='Test()'> Click me </span> <hr> <span id='bla2& ...

Assess the scss styles specific to components following the global min.css in a React application

ISSUE Imagine we have a min.css file that needs to be imported globally: index.js import ReactDOM from "react-dom"; import App from "src/App"; import "library/library.min.css"; ReactDOM.render(<App />, document.getE ...

Uploading data using jQuery and submitting it using AJAX techniques

I am currently working on uploading and posting data to a modal window. Although my code works perfectly in IE 10, Chrome, Firefox, Opera, it seems to have some issues in IE versions below 10. Does anyone have any ideas on how I can fix this "bug" or what ...

Disabled screen rotation -> hidden background

I tried implementing a media query to "lock" the orientation on my mobile site, but unfortunately, my background image isn't displaying at all. After adding the media query, I included my stylesheet using the link: CSS body { padding:0; marg ...

Using "overflow-x: hidden" is ineffective on mobile devices

I'm facing an issue where the CSS property overflow-x: hidden is not working on mobile devices. Here is a snippet of my HTML code: <div class="topbar"> <div class="navbar-brand float-left"> <a href="#"><img src="asset ...

Is it feasible to dynamically insert and delete elements in React?

I'm currently in the process of rebuilding a project, specifically a drag and drop website builder, using React after it was originally built with a heavy reliance on jQuery. My main challenge lies in being able to dynamically add and remove elements ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

jQuery Function malfunctioning after initial click

I have developed a function that plays and pauses music. It is designed to be simple and lightweight for small audio samples, with basic play and stop functionalities. The issue I'm encountering is that after playing the music for the second time, the ...

What steps do I need to take to generate a terrain similar to this using Three.js?

Trying to construct a terrain based on a heightmap with an enclosed bottom layer. Refer to this example for clarification: The current function for generating the terrain is as follows: var img = document.getElementById("landscape-image"); var numSegment ...

Response from Vimeo's AJAX API

I am having trouble retrieving the AJAX response from Vimeo to extract a thumbnail without using JQuery. Even though I can see the response data in JSON format when I type the response query (http://vimeo.com/api/v2/video/30408418.json) into the browser an ...

"The value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

Unlimited scrolling gallery with multiple rows

I am looking for a way to create a multi-row infinite loop scrolling gallery using html, css, and javascript. Can anyone help me with this? ...

Using the max-width property with Semantic UI Dropdown in ReactJS

I'm struggling to determine how to adjust the max-width of the Dropdown element in ReactJS. I attempted the following: .Menu Dropdown { max-width: 5rem !important; } Unfortunately, this did not work as expected. The dropdowns are taking up too m ...

Sending the handleSubmit() function to the child component does not alter the state of the parent component

I just started learning React and Javascript. Currently, I am working on a form where users can specify the details of a "Mob". Upon submitting the form, I anticipate that handleSubmit() (which is passed down from the parent component) will update the sta ...

Testing Angular 16 Component with Jasmine Spy and callFake Strategy

I've encountered an issue while trying to test my component unit. The problem arises when I call the product-list.component.ts from my product.service.ts. While my product.service.spec.ts is successful, the product-list.component.spec.ts fails as the ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

Verify if the program is operating on a server or locally

My current project involves a website with a game client and a server that communicate via sockets. The issue I'm facing is how to set the socket url depending on whether the code is running on the server or my local PC. During testing and debugging, ...