1. Home
HTML

Learn HTML: A Comprehensive Tutorial for Beginners | Step-by-Step Guide

Learn HTML from scratch! Our tutorial covers basics to advanced concepts. Start coding websites today with step-by-step guidance.

  • 49
  • 12 Hours
right-top-arrow
36

HTML Drag and Drop

Updated on 19/08/2024451 Views

The Drag and Drop API in HTML5 gives developers a collection of features and events for creating interactive and intuitive drag-and-drop features in web pages and online applications. It has paved the way for a lot of actions we take on a daily basis online. This tutorial is a comprehensive guide to teach you all about HTML drag and Drop.

Having worked as a web developer myself, I can say with confidence that the HTML drag and drop feature is used on a regular basis when developing intuitive web pages.

Introduction to HTML Drag and Drop

Before getting into any advanced concepts, let me brief you about what exactly HTML drag and drop is. HTML drag and drop is a user interaction approach that allows you to click and hold an object, move it to a new position, and then drop it there. In the context of HTML, this feature allows for dynamic and interactive user experiences on web pages. It lets users transfer components like photos, text, or files around a web page or between applications conveniently. Now let me move on to the next section and discuss where HTML drag and drop is used.

HTML Drag and Drop Use Cases

The HTML drag and drop element is extremely useful. I am sure you have used it multiple times surfing the internet. Let me discuss some of the ways drag and drop HTML5 can be used.

  • File uploads: The HTML drag and drop feature is useful for file uploads. It enables users to drag files from their computer and drop them into a specific location usually marked on the web page for upload. This can make it easier, faster, and more intuitive for users to upload many files at the same time.
  • Games and Puzzles: HTML drag and drop can be used to construct interactive games and puzzles that need users to drag and drop pieces to solve problems, arrange objects, or perform tasks. This can be everything from basic matching games to more complicated interactive experiences.
  • Content reordering: HTML drag and drop is a commonly used method for reordering elements in lists, grids, and other layouts online on web pages. Users can simply rearrange objects by dragging them into different positions. One such example is rearranging jobs on a to-do list.
  • Interactive Interfaces: HTML drag and drop can be used to construct interactive interfaces, such as draggable widgets or components that allow users to move and manipulate them within a web application. Examples include draggable panels in a dashboard and changeable layouts in a design tool.
  • File Management: HTML Drag and drop can be used to move files between folders or categories in web-based file management apps. Users can drag and drop files from one spot to another to better organize their files.

Drag and Drop events

There are many events in the drag section and drop section of the HTML drag and drop. Let me discuss some of the events here down below with you.

  • dragstart: This event occurs when the user begins to drag an element that has been tagged as draggable in the script. It is commonly used to prepare the data that will be transported during the drag operation.
  • drag: The drag event is triggered constantly while the draggable element is being dragged. It can be used for a variety of purposes, including changing the visual appearance of a draggable element or performing additional operations when dragging.
  • dragenter: This event takes place when a dragged element enters a drop target (i.e., an element that accepts drops). It's frequently used to provide visual feedback to the user, such as illuminating the drop target to show that it can accept the dragged item.
  • dragover: The dragover event is triggered continually when a draggable element is dragged over a drop target. You should know that most browsers automatically block you from dropping material into non-droppable locations.
  • dragleave: This event occurs when a dragged element leaves a drop target. It is typically used to delete any visual indicators or effects that were applied while the element was inside the drop target.
  • drop: The drop event occurs when a draggable element is dropped onto a drop target. This event is often used to handle dropped content and take any appropriate actions. In the example code, the drop event is handled by the drop function, which obtains and processes the data transferred during the drag action.
  • dragend: The dragend event is triggered after the user completes dragging an element. This event is useful for cleaning up or finishing drag-related actions. After the drag operation is complete, you may reset the visual state of the dragged element or refresh the UI.

HTML Drag and Drop Examples

Let me share a couple of examples of a program demonstrating HTML drag and drop. This program is used to make a fruit basket. You can drag and drop fruit elements into the fruit basket.

Fruit basket example

HTML drag and drop example

Output HTML drag and drop example

Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>HTML Drag and Drop Example</title>

<style>

.drag-container {

display: flex;

gap: 10px;

}

.drag-item {

width: 100px;

height: 100px;

background-color: lightblue;

text-align: center;

line-height: 100px;

cursor: grab;

}

.drop-container {

min-height: 200px;

border: 2px dashed gray;

margin-top: 20px;

padding: 10px;

}

.drop-container.active {

border-color: green;

}

</style>

</head>

<body>

<div class="drag-container">

<div class="drag-item" draggable="true" ondragstart="drag(event)">Apple</div>

<div class="drag-item" draggable="true" ondragstart="drag(event)">Orange</div>

<div class="drag-item" draggable="true" ondragstart="drag(event)">Banana</div>

</div>

<div class="drop-container" ondragover="allowDrop(event)" ondrop="drop(event)">

Fruit Basket

</div>

<script>

function drag(event) {

event.dataTransfer.setData("text/plain", event.target.innerText);

}

function allowDrop(event) {

event.preventDefault();

event.target.classList.add('active');

}

function drop(event) {

event.preventDefault();

event.target.classList.remove('active');

var data = event.dataTransfer.getData("text/plain");

event.target.innerHTML += "<div>" + data + "</div>";

}

</script>

</body>

</html>

In the above example, we created a drag-and-drop interface in which you may move the fruits “apple”, ”orange”, and “banana” elements to the "fruits basket." When you drag and drop an object into the drop zone, it creates a new div with the item's text.

Sorting game example

In this example, I will show you how you can build a game where you have to segregate the items on the basis of numbers and alphabets.

Sorting Game example

Output for Sorting game example

Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>HTML Drag and Drop Example 2</title>

<style>

body {

font-family: Arial, sans-serif;

}

.drag-container {

display: flex;

gap: 10px;

margin-bottom: 20px;

}

.drag-item1 {

width: 100px;

height: 50px;

background-color: lightblue;

text-align: center;

line-height: 50px;

cursor: grab;}

.drag-item2 {

width: 100px;

height: 50px;

background-color: lightgreen;

text-align: center;

line-height: 50px;

cursor: grab;}

.drop-container {

min-height: 100px;

border: 2px dashed gray;

padding: 10px;

background-color: yellow;

}

</style>

</head>

<body>

<h2> Sorting Game </h2>

<div class="drag-container">

<div class="drag-item1" draggable="true" ondragstart="drag(event)">Item 1</div>

<div class="drag-item1" draggable="true" ondragstart="drag(event)">Item 2</div>

<div class="drag-item1" draggable="true" ondragstart="drag(event)">Item 3</div>

<div class="drag-item2" draggable="true" ondragstart="drag(event)">Item a</div>

<div class="drag-item2" draggable="true" ondragstart="drag(event)">Item b</div>

<div class="drag-item2" draggable="true" ondragstart="drag(event)">Item c</div>

</div>

<div class="drop-container" id="dropZone1" ondragover="allowDrop(event)" ondrop="drop(event, 'dropZone1')">

Drop Zone For Numbers

</div>

<div class="drop-container" id="dropZone2" ondragover="allowDrop(event)" ondrop="drop(event, 'dropZone2')">

Drop Zone For Alphabets

</div>

<script>

function drag(event) {

event.dataTransfer.setData("text/plain", event.target.innerText);

}

function allowDrop(event) {

event.preventDefault();

}

function drop(event, dropZoneId) {

event.preventDefault();

var data = event.dataTransfer.getData("text/plain");

var droppedItem = document.createElement("div");

droppedItem.textContent = data;

document.getElementById(dropZoneId).appendChild(droppedItem);

}

</script>

</body>

</html>

In the above example,

  • The.drag-container has six draggable items: Item 1, Item 2, Item 3, Item a, Item b, and Item c.
  • There are two drop zones (Drop Zone for Numbers and Drop Zone for Alphabets) with distinct IDs.
  • The drag function defines the data that will be sent during the drag action.
  • The allowDrop function disables the normal behavior of allowing dropping inside drop zones.
  • The drop function responds to the drop event by creating a new div with the dropped item's text content and attaching it to the specified drop zone depending on the dropZoneID.

In Conclusion

In conclusion, drag and drop may significantly improve the user experience, making web apps more engaging and efficient, when implemented correctly and with accessibility in mind. Whether you're creating a file management system, a drag-and-drop game, or a workflow tool, HTML drag and drop provides a flexible and user-friendly option for interactive web development. You can also use HTML drag and drop example codepen which is an online open source platform much like GitHub to practice this concept.

If you want to learn more advanced concepts of HTML and web development, I would suggest doing a certified course on web development on the basics of HTML. I would strongly suggest upGrad. Their courses are some of the best in the industry. Their courses are in collaboration with some of the best universities around the world. Some of the best professors in the field curate the courses.

Frequently Asked Questions

  1. What is HTML drag and drop?

HTML drag and drop allows users to drag and drop components (such as images, text, or files) from one position on a web page to another. It's an easy way to interact with content and move objects naturally.

  1. How does HTML drag and drop work?

HTML drag and drop uses a combination of JavaScript and Drag and Drop HTML5 API. First, use the draggable attribute to denote that an element is draggable. When a user begins dragging an element, events such as dragstart, drag, and dragend are triggered. You can then create drop zones by using elements with ondragover and ondrop event handlers to specify where the draggable element can be dropped.

  1. Which browsers support HTML drag and drop?

Most recent web browsers enable HTML drag & drop. The list includes.

  • Google Chrome
  • Mozilla Firefox
  • Safari
  • Microsoft Edge
  • Opera
  1. What can I drag and drop with HTML?

HTML drag and drop allows you to move photos, text, uploadable files, and custom HTML elements around. We can program the function to accept almost any element type.

  1. What are some common use cases for HTML drag and drop?

Some common uses for HTML drag & drop include rearranging items in a list or grid, uploading files by dragging them to a selected drop zone and creating interactive drag-and-drop games and puzzles.

  1. Is HTML drag and drop accessible?

HTML drag and drop can be made accessible with good implementation. This includes guaranteeing keyboard accessibility and giving alternative solutions for users who are unable to drag and drop with a mouse, such as using buttons or other controls to perform the same tasks.

  1. What is drag and drop with an example?

HTML drag and drop occurs when you click and hold on an object, drag it to a new area, and then release it to drop it there. For example, drag and drop files onto a website's upload box.

Mukesh kumar

Mukesh kumar

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...