The Wayback Machine - https://web.archive.org/web/20240625022707/https://www.geeksforgeeks.org/html-drag-and-drop/
Open In App

HTML Drag and Drop

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Drag and Drop is a very interactive and user-friendly concept that makes it easier to move an object to a different location by grabbing it. This allows the user to click and hold the mouse button over an element, drag it to another location, and release the mouse button to drop the element there.

In HTML5 Drag and Drop are much easier to code and any element in it is draggable.

Drag and Drop Events

Events

Description

ondrag

It is used to use when the element or text selection is being dragged in HTML.

ondragstart

It is used to call a function, drag(event), that specifies what data to be dragged

ondragenter

It is used to determine whether or not the drop target is to accept the drop. If the drop is to be accepted, then this event has to be canceled.

ondragleave

It occurs when the mouse leaves an element before a valid drop target while the drag is occurring.

ondragover

It specifies where the dragged data can be dropped.

ondrop

It specifies where the drop has occurred at the end of the drag operation.

ondragend

It occurs when the user has finished dragging an element.

The Data Transfer Object

The data transfer property is used when the whole process of Drag and Drop happens. It is used to hold the dragged data from the source and drop it to the desired location. These are the properties associated with it:

Property

Description

dataTransfer.setData(format, data)

Sets the data to be dragged.

dataTransfer.clearData(format)

Clears data, if a format is specified, it removes only that specific data.

dataTransfer.getData(format)

Returns data of the specified format; returns an empty string if no data.

dataTransfer.types

Returns an array of all formats set during dragstart.

dataTransfer.files

Returns all files to be dropped.

dataTransfer.setDragImage(element, x, y)

Displays an existing image during drag, with coordinates for drop location

dataTransfer.addElement(element)

Adds the specified element as a drag feedback image.

dataTransfer.effectAllowed(value)

Specifies allowed operations for the user: none, copy, link, move, etc.

dataTransfer.dropEffect(value)

Controls feedback during dragenter/dragover events, indicating operation type: none, copy, link, move.

Approach for Drag and Drop in HTML

  • Set an element as draggable with the draggable attribute: <img draggable="true">.
  • Specify the drag behavior using the ondragstart attribute, calling a function (drag(event)) to define the data to be dragged with event.dataTransfer.setData().
  • Utilize the ondragover event to determine where the data can be dropped. Prevent default behavior with event.preventDefault() to enable the drop.
  • Implement the ondrop event to perform the actual drop action.

Examples Showing Drag and Drop in HTML

1. Drag and Drop of Image in HTML:

Example: This example shows the drag & drop of an image in HTML.

HTML




<!DOCTYPE HTML>
<html>
   
<head>
    <style>
      #getData {
          width: 250px;
          height: 200px;
          padding: 10px;
          border: 1px solid #4f4d4d;
      }
    </style>
    <script>
      function allowDrop(even) {
          even.preventDefault();
      }
 
      function drag(even) {
          even.dataTransfer.setData("text", even.target.id);
      }
 
      function drop(even) {
          even.preventDefault();
          var fetchData = even.dataTransfer.getData("text");
          even.target.appendChild(document.getElementById(fetchData));
      }
    </script>
</head>
 
<body>
    <h3>Drag the GeekforGeeks image into the rectangle:</h3>
    <div id="getData"
         ondrop="drop(event)"
         ondragover="allowDrop(event)">
      </div>
    <br>
    <img id="dragData"
         src="gfg.png"
         draggable="true"
         ondragstart="drag(event)"
         width="250"
         height="200">
</body>
   
</html>


Output:

Dragging the image into the box

2. Implementation of Draggable Property:

Example: This example shows the drag & drop of an image in HTML.

HTML




<!DOCTYPE HTML>
<html>
 
<head>
    <title>Drag and Drop box</title>
    <script>
        function allowDrop(ev) {
            ev.preventDefault();
        }
 
        function dragStart(ev) {
            ev.dataTransfer.setData("text", ev.target.id);
        }
 
        function dragDrop(ev) {
            ev.preventDefault();
            let data = ev.dataTransfer.getData("text");
            ev.target.appendChild(document.getElementById(data));
        }
    </script>
    <style>
        #box {
            margin: auto;
            width: 50%;
            height: 200px;
            border: 3px solid green;
            padding: 10px;
        }
 
        #box1,
        #box2,
        #box3 {
            float: left;
            margin: 5px;
            padding: 10px;
        }
 
        #box1 {
            width: 50px;
            height: 50px;
            background-color: #F5B5C5;
        }
 
        #box2 {
            width: 100px;
            height: 100px;
            background-color: #B5D5F5;
        }
 
        #box3 {
            width: 150px;
            height: 150px;
            background-color: #BEA7CC;
        }
 
        p {
            font-size: 20px;
            font-weight: bold;
            text-align: center;
        }
 
        .gfg {
            font-size: 40px;
            color: #009900;
            font-weight: bold;
            text-align: center;
        }
    </style>
</head>
 
<body>
    <div class="gfg">GeeksforGeeks</div>
    <p>Drag and drop of boxes</p>
    <div id="box">
        <div id="box1" draggable="true"
             ondragstart="dragStart(event)">
        </div>
        <div id="box2" draggable="true"
             ondragstart="dragStart(event)">
        </div>
        <div id="box3" ondrop="dragDrop(event)"
             ondragover="allowDrop(event)">
        </div>
    </div>
</body>
 
</html>


Output:

3. Using Image Drag and Drop:

Example: Implementation of Drop and Drop in HTMl using the Images.

HTML




<!DOCTYPE HTML>
<html>
   
<head>
    <script>
      function allowDrop(ev) {
          ev.preventDefault();
      }
 
      function dragStart(ev) {
          ev.dataTransfer.setData("text", ev.target.id);
      }
 
      function dragDrop(ev) {
          ev.preventDefault();
          var data = ev.dataTransfer.getData("text");
          ev.target.appendChild(document.getElementById(data));
      }
    </script>
    <style>
      .div1 {
          width: 240px;
          height: 75px;
          padding: 10px;
          border: 1px solid black;
          background-color: #F5F5F5;
      }
 
      p {
          font-size: 20px;
          font-weight: bold;
      }
 
      .gfg {
          font-size: 40px;
          color: #009900;
          font-weight: bold;
      }
    </style>
</head>
 
<body>
    <div class="gfg">GeeksforGeeks</div>
    <p>Image Drag and Drop in boxes</p>
    <div class="div1"
         ondrop="dragDrop(event)"
         ondragover="allowDrop(event)">
     <img id="drag1"
          src=
          draggable="true"
          ondragstart="dragStart(event)"
          width="220"
          height="70">
       </div>
    <br>
    <div class="div1"
         ondrop="dragDrop(event)"
         ondragover="allowDrop(event)">
    </div>
</body>
   
</html>


Output:

Dragging the image into another box

4. Dragging Using Text in Rectangular Box:

Example: Implementation of dragging the text in the rectangular box.

HTML




<!DOCTYPE HTML>
<html>
   
<head>
    <title>Draggable Text</title>
    <style>
      .dropbox {
          width: 350px;
          height: 40px;
          padding: 15px;
          border: 1px solid #292828;
      }
 
      h1 {
          color: green;
      }
    </style>
    <script>
      function droppoint(event) {
          var data = event.dataTransfer.getData("Text");
          event.target.appendChild(document.getElementById(data));
          event.preventDefault();
      }
 
      function allowDropOption(event) {
          event.preventDefault();
      }
 
      function dragpoint(event) {
          event.dataTransfer.setData("Text", event.target.id);
      }
    </script>
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h3>Drag the text in the rectangle</h3>
        <div class="dropbox"
             ondrop="droppoint(event)"
             ondragover="allowDropOption(event)">
          </div>
        <p id="drag1"
           draggable="true"
           ondragstart="dragpoint(event)">
       GeeksforGeeks: A computer science portal for geeks.
          </p>
    </center>
</body>
   
</html>


Output:

Dragging the text into the box

Supported Browser:

  • Google Chrome 4.0
  • Microsoft Edge 9.0
  • Firefox 3.5
  • Opera 6.0
  • Safari 12.0


Previous Article
Next Article

Similar Reads

Angular PrimeNG Drag and Drop Drop Indicator
Angular PrimeNG is a collection of Interactive UI components for Angular applications. Developers can use these components to make beautiful and responsive web interfaces in no time as most of the components have all the necessary functions implemented. In this article, we will see Angular PrimeNG Drag and Drop Drop Indicator. The Drag and Drop dir
2 min read
How to create a drag and drop feature for reordering the images using HTML CSS and jQueryUI ?
In this article, we are given an images gallery and the task is to re-arrange the order of images in the list or grid by dragging and dropping. The jQuery UI framework provides a sortable() function that helps in re-ordering list items by using the mouse. With this functionality, the list items become interchangeable. The jQuery UI provides a sorta
3 min read
Web API HTML Drag and Drop
In this article, we will learn Web API HTML drag and drop functioning with various methods. There is the HTML Drag and Drop feature which is used to make user interaction by enabling them to drag some boxes made with any tag and drop them like text and images into the dropping regions that are created on DOM. This can be done by using functionality
4 min read
Build A Drag & Drop Kanban Board using HTML CSS & JavaScript
A Kanban board is a project management tool designed to visualize work, limit work in progress, and maximize efficiency. With drag &amp; drop functionality, users can easily move tasks between different stages of completion, providing a visual representation of the workflow. Approach:The below defined steps can be utilised to build and design a Kan
4 min read
Creating a Customizable Dashboard with React and Drag-and-Drop functionality
In this article, we will create a Dashboard with a drag-and-drop functionality using React JS. This project basically implements useState principles and the use of vite to set up the run time environment of React and JavaScript. The drag and drop functionality will enable the user to drag from one container and drop the picked element into the othe
4 min read
Sortable Drag and Drop with React and Tailwind CSS
In this tutorial, we'll learn how to create a sortable drag-and-drop feature in a React application using Vite for quick and efficient development, along with Tailwind CSS for styling. This feature allows users to reorder items in a list by dragging and dropping them, enhancing the user experience of your web application. Output Preview: Let us hav
3 min read
How to create a To-Do list using Drag and Drop in Angular 7 ?
We can easily create a To-Do list using Drag-Drop module provided by angular Component Development Kit (CDK). First of all, create an angular component by using the following command- ng g c To-Do Now import CdkDragDrop, moveItemInArray, transferArrayItem from @angular/cdk/drag-drop to our to-Do component, Writing the code for component view: Creat
2 min read
Drag and Drop Files in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.There are several differences between a Drag-and-Dr
8 min read
How to Drag and Drop Images using HTML5 ?
In this article, we will see how to create a drag and drop functionality using HTML5. Approach: The following approach will be implemented to Drag and Drop Images using HTML5. We have given a rectangle area and an image, the task is to drag the image and drop it into the rectangle.We have to enable ondrop="drop(event)" and ondragover="allowDrop(eve
2 min read
Angular PrimeNG Drag and Drop Events
Angular PrimeNG is a UI component library for Angular Applications. It offers many pre-built themes and UI components for a variety of tasks like inputs, menus, charts, Buttons, etc. In this article, we will learn about Angular PrimeNG Drag and Drop Events. The Drag and Drop directives (pDraggable and pDroppable) are used to apply drag and drop beh
6 min read
three90RightbarBannerImg