Webapps can be useful for data collection/ingestion. If the mechanism to collect and store data is easy to use, lot of useful data can be amassed for data processing. One easy to way to move data from one location to another is the Drag and drop functionality on webapps.
In this post, I show three examples for how to move and store HTML element data and files using JavaScript drag and drop programming.
Example 0: Drag and drop an HTML element
<h1 id="Example-Drag-and-Drop-HTML-text-elements">Example 0: Drag and Drop HTML text/elements</h1> <div id="HTML_text" draggable="true" class="dragElement">HTML text</div> <br><br> <div id="dropArea" class="dropArea"> Drop for Example 0 & 1</div> <style> .dropArea { height: 200px; width: 200px; border-radius: 15px; border: 0.25px solid black; background-color: #7084c4; } .HTML_text { cursor: move; } </style> <script> var example; var other_data_related_to_dragEvent = {}; var html_element_drag_list_metaData = []; // ---------------------------------------------------- // Drag functionality: Example 0 // ---------------------------------------------------- document.getElementById("HTML_text").addEventListener("dragstart", processEvent_drag_example0, false); // document.getElementById("HTML_text").addEventListener("dragend", processEvent_drag_example0, false); // to stop function processEvent_drag_example0(event) { example = 0; event.dataTransfer.setData('text/plain', event.target.id); } // ---------------------------------------------------- // ---------------------------------------------------- // Drop functionality: Example 0 and 1 // ---------------------------------------------------- document.getElementById("dropArea").addEventListener("drop", processEvent_drop, false); document.getElementById("dropArea").addEventListener("dragover", processEvent_dragover, false); function processEvent_drop(event) { // Stop defaults and allow drop events event.preventDefault(); // Detects files dragged from pc html_element_drag_list_metaData.push(event.dataTransfer.files); console.log('html_element_drag_list_metaData: ', html_element_drag_list_metaData); // Detects html elements dragged from the html page const data = event.dataTransfer.getData('text/plain'); console.log('data: ', data); if (data.length != 0) { // find the draggable element based on the data const dragElement = document.getElementById(data); console.log('dragElement: ', dragElement); // Append the draggable element event.target.appendChild(dragElement); } } function processEvent_dragover(event) { // Stop defaults and allow drop events event.preventDefault(); } // ------------------------------------------------- </script>
Before dragging and dropping the HTML text (HTML text) to the purple dropArea
After dragging and dropping the HTML text (HTML text) to the purple dropArea
In example 0, the HTML text element was actually moved into the drop area. The id of the div for HTML text appeared in the variable data, thus one can keep track of the element ids inside the dropArea. This example is useful for organizing/storing existing html written on a webapp, but in most data ingestion situation one wants to organize/store data from different places.
Example 1: a file upload is represented as a draggable HTML element/emoji
This example is a cross between dragging an HTML element and dragging a file. One can select a file using the Browse button; drag a file to the browse button or click on the browse button to select a file. Then an emoji appears after the file has been selected, the appearance of the emoji represents the file in terms of an HTML element. The HTML element emoji, representative of a file, can then be dragged to the dropArea for data ingestion/storage.
<h1 id="Example-Click-button-create-drag-and-drop-elements">Example 1: Click button create drag and drop elements</h1> <input type="file" id="upload_file" accept="audio/*" style="display:block" multiple> <div id="file_name" style="display:none"></div> <div id="base64_string" style="display:none"></div> <div id="base64_string_icon" draggable="true" class="dragElement" style="display:none">?</div> <br><br> <div id="dropArea" class="dropArea"> Drop for Example 0 & 1</div> <style> .dropArea { height: 200px; width: 200px; border-radius: 15px; border: 0.25px solid black; background-color: #7084c4; } .HTML_text { cursor: move; } </style> <script> var example; var other_data_related_to_dragEvent = {}; var html_element_drag_list_metaData = []; // ---------------------------------------------------- // Drag functionality: Example 1 // ---------------------------------------------------- // The eventlistener needs to be always running, to detect which file the user selected with browse document.getElementById("upload_file").addEventListener("change", previewInput_drop, false); async function previewInput_drop(event) { // Take the first file const file = event.target.files[0]; // first file in the list of selected files, better for selecting multiple files at one time // console.log("file :", file); document.getElementById("file_name").innerHTML = file.name; // --------------------- const reader = new FileReader(); reader.onload = async function(e){ document.getElementById("base64_string").innerHTML = e.target.result; document.getElementById("base64_string_icon").style.display = "block"; } reader.readAsDataURL(file); } document.getElementById("base64_string_icon").addEventListener("dragstart", processEvent_drag_example1, false); function processEvent_drag_example1(event) { example = 1; event.dataTransfer.setData('text/plain', event.target.id); } // ---------------------------------------------------- // ---------------------------------------------------- // Drop functionality: Example 0 and 1 // ---------------------------------------------------- document.getElementById("dropArea").addEventListener("drop", processEvent_drop, false); document.getElementById("dropArea").addEventListener("dragover", processEvent_dragover, false); function processEvent_drop(event) { // Stop defaults and allow drop events event.preventDefault(); // Detects files dragged from pc html_element_drag_list_metaData.push(event.dataTransfer.files); console.log('html_element_drag_list_metaData: ', html_element_drag_list_metaData); // Detects html elements dragged from the html page const data = event.dataTransfer.getData('text/plain'); console.log('data: ', data); if (data.length != 0) { // find the draggable element based on the data const dragElement = document.getElementById(data); console.log('dragElement: ', dragElement); // Append the draggable element event.target.appendChild(dragElement); } } function processEvent_dragover(event) { // Stop defaults and allow drop events event.preventDefault(); } // ------------------------------------------------- </script>
Before selecting a file
Dragged a file to the browse button
Dragged the representative file emoji to the dropArea
Example 2: Drag and drop an HTML element
In this example, one can efficiently drag multiple files to the dropArea at one time.
<h1 id="Example-Drag-and-drop-files">Example 2: Drag and drop files</h1> <input type="file" id="upload_file_dragdrop" style="display:block" class="dropArea1" multiple> <br><br> <button id="use_moved_data" onclick="use_moved_data()">use_moved_data</button> <!-- ---------------------------------------- --> <!-- CSS --> <style> .dropArea1 { height: 200px; width: 200px; border-radius: 15px; border: 0.25px solid black; background-color: #56b06e; } </style> <!-- ---------------------------------------- --> <script> var other_data_related_to_dragEvent = {}; var html_element_drag_list_metaData = []; // ---------------------------------------------------- // Drag and Drop functionality: Example 2 // ---------------------------------------------------- document.getElementById("upload_file_dragdrop").addEventListener("change", previewInput, false); async function previewInput(event) { // For multiple files const allFiles = event.target.files; // console.log("allFiles :", allFiles); var i = 0; while (i < allFiles.length) { const file = allFiles[i]; // console.log("file :", file); await obtain_fileInfo(file) .then(base64str => { other_data_related_to_dragEvent[file.name] = base64str; }) .catch(error => console.error(error)); i = i + 1; } // --------------------- } async function obtain_fileInfo(file) { var base64_string = await new Promise((resolve) => { const reader = new FileReader(); reader.onload = async function(e){ resolve(e.target.result); // inside resolve is the value that the function returns }; reader.readAsDataURL(file); }); return base64_string; } // ---------------------------------------------------- async function use_moved_data() { console.log('html_element_drag_list_metaData: ', html_element_drag_list_metaData); console.log('other_data_related_to_dragEvent: ', other_data_related_to_dragEvent); } </script>
Before dragging files into the dropArea
After dragging files into the dropArea and pushing the use_moved_data button
We can see an the base64 string data of the three files that were dragged into the dropArea! The base64 string data can then be saved as a blob object and transferred to across the Internet.
I hope these ways to drag and drop HTML elements and files helps someone.
Happy Practicing! ?
? GitHub | ? Practicing Datscy @ Dev.to | ? Practicing Datscy @ Medium
References
- How to Create Drag and Drop Functionality in JavaScript: A Step-by-Step Tutorial: https://medium.com/@future_fanatic/how-to-create-drag-and-drop-functionality-in-javascript-a-step-by-step-tutorial-8ea236ef9416
- Read files in JavaScript: https://web.dev/articles/read-files
The above is the detailed content of Drag and Drop HTML elements and files. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools