Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

HTML Drag and Drop API

HTML Drag and Drop interfaces enable applications to use drag-and-drop features in browsers.

The user may selectdraggable elements with a mouse, drag those elements to adroppable element, and drop them by releasing the mouse button. A translucent representation of thedraggable elements follows the pointer during the drag operation.

You can customize which elements can becomedraggable, the type of feedback thedraggable elements produce, and thedroppable elements.

This overview of HTML Drag and Drop includes a description of the interfaces, basic steps to add drag-and-drop support to an application, and an interoperability summary of the interfaces.

Concepts and usage

Drag Events

HTML drag-and-drop uses theDOM event model anddrag events inherited frommouse events. A typicaldrag operation begins when a user selects adraggable element, continues when the user drags the element to adroppable element, and then ends when the user releases the dragged element.

During drag operations, several event types are fired, and some events might fire many times, such as thedrag anddragover events.

Eachdrag event type has an associated event handler:

EventFires when...
drag...adragged item (element or text selection) is dragged.
dragend...a drag operation ends (such as releasing a mouse button or hitting the Esc key; seeFinishing a Drag.)
dragenter...a dragged item enters a valid drop target. (SeeSpecifying Drop Targets.)
dragleave...a dragged item leaves a valid drop target.
dragover...a dragged item is being dragged over a valid drop target, every few hundred milliseconds.
dragstart...the user starts dragging an item. (SeeStarting a Drag Operation.)
drop...an item is dropped on a valid drop target. (SeePerforming a Drop.)

Note:Neitherdragstart nordragend events are fired when dragging a file into the browser from the OS.

The basics

This section is a summary of the basic steps to add drag-and-drop functionality to an application.

Identify what is draggable

Making an elementdraggable requires adding thedraggable attribute and thedragstart event handler, as shown in the following code sample:

html
<p draggable="true">This element is draggable.</p>
js
// Get the element by idconst element = document.getElementById("p1");// Add the ondragstart event listenerelement.addEventListener("dragstart", (ev) => {  // Add the target element's id to the data transfer object  ev.dataTransfer.setData("text/plain", ev.target.id);});

For more information, see:

Define the drag's data

The application is free to include any number of data items in a drag operation. Each data item is a string of a particulartype — typically a MIME type such astext/html.

EachDragEvent has adataTransfer property thatholds the event's data. This property (which is aDataTransfer object) also has methods tomanage drag data. ThesetData() method is used to add an item to the drag data, as shown in the following example.

js
function dragstartHandler(ev) {  // Add different types of drag data  ev.dataTransfer.setData("text/plain", ev.target.innerText);  ev.dataTransfer.setData("text/html", ev.target.outerHTML);  ev.dataTransfer.setData(    "text/uri-list",    ev.target.ownerDocument.location.href,  );}
  • For a list of common data types used in drag-and-drop (such as text, HTML, links, and files), seeRecommended Drag Types.
  • For more information about drag data, seeDrag Data.

Define the drag image

By default, the browser supplies an image that appears beside the pointer during a drag operation. However, an application may define a custom image with thesetDragImage() method, as shown in the following example.

js
// Create an image and then use it for the drag image.// NOTE: change "example.gif" to a real image URL or the image// will not be created and the default drag image will be used.let img = new Image();img.src = "example.gif";function dragstartHandler(ev) {  ev.dataTransfer.setDragImage(img, 10, 10);}

Learn more about drag feedback images in:

Define the drop effect

ThedropEffect property is used to control the feedback the user is given during a drag-and-drop operation. It typically affects which cursor the browser displays while dragging. For example, when the user hovers over a drop target, the browser's cursor may indicate the type of operation that will occur.

Three effects may be defined:

  1. copy indicates that the dragged data will be copied from its present location to the drop location.
  2. move indicates that the dragged data will be moved from its present location to the drop location.
  3. link indicates that some form of relationship or connection will be created between the source and drop locations.

During the drag operation, drag effects may be modified to indicate that certain effects are allowed at certain locations.

The following example shows how to use this property.

js
function dragstartHandler(ev) {  ev.dataTransfer.dropEffect = "copy";}

For more details, see:

Define a drop zone

By default, the browser prevents anything from happening when dropping something onto most HTML elements. To change that behavior so that an element becomes adrop zone or isdroppable, the element must listen to bothdragover anddrop events.

The following example shows how to use those events.

html
<p>Drop Zone</p>
js
const target = document.getElementById("target");target.addEventListener("dragover", (ev) => {  ev.preventDefault();  ev.dataTransfer.dropEffect = "move";});target.addEventListener("drop", (ev) => {  ev.preventDefault();  // Get the id of the target and add the moved element to the target's DOM  const data = ev.dataTransfer.getData("text/plain");  ev.target.appendChild(document.getElementById(data));});

Note that each handler callspreventDefault() to prevent additional event processing for this event (such astouch events orpointer events).

For more information, see:

Handle the drop effect

The handler for thedrop event is free to process the drag data in an application-specific way.

Typically, an application uses thegetData() method to retrieve drag items and then process them accordingly. Additionally, application semantics may differ depending on the value of thedropEffect and/or the state of modifier keys.

The following example shows a drop handler getting the source element'sid from the drag data, and then using theid to move the source element to the drop element:

html
<p draggable="true">This element is draggable.</p><div>Drop Zone</div>
js
const source = document.getElementById("p1");const target = document.getElementById("target");source.addEventListener("dragstart", (ev) => {  // Add the target element's id to the data transfer object  ev.dataTransfer.setData("application/my-app", ev.target.id);  ev.dataTransfer.effectAllowed = "move";});target.addEventListener("dragover", (ev) => {  ev.preventDefault();  ev.dataTransfer.dropEffect = "move";});target.addEventListener("drop", (ev) => {  ev.preventDefault();  // Get the id of the target and add the moved element to the target's DOM  const data = ev.dataTransfer.getData("application/my-app");  ev.target.appendChild(document.getElementById(data));});

For more information, see:

Drag end

At the end of a drag operation, thedragend event fires at thesource element — the element that was the target of the drag start.

This event fires regardless of whether the drag completed or was canceled. Thedragend event handler can check the value of thedropEffect property to determine if the drag operation succeeded or not.

For more information about handling the end of a drag operation, see:

Interfaces

The HTML Drag and Drop interfaces areDragEvent,DataTransfer,DataTransferItem andDataTransferItemList.

TheDragEvent interface has a constructor and onedataTransfer property, which is aDataTransfer object.

DataTransfer objects include the drag event's state, such as the type of drag being done (likecopy ormove), the drag's data (one or more items), and the MIME type of eachdrag item.DataTransfer objects also have methods to add or remove items to the drag's data.

TheDragEvent andDataTransfer interfaces should be the only ones needed to add HTML Drag and Drop capabilities to an application.

EachDataTransfer object contains anitems property, which is alist ofDataTransferItem objects. ADataTransferItem object represents a singledrag item, each with akind property (eitherstring orfile) and atype property for the data item's MIME type. TheDataTransferItem object also has methods to get the drag item's data.

TheDataTransferItemList object is a list ofDataTransferItem objects. The list object has methods to add a drag item to the list, remove a drag item from the list, and clear the list of all drag items.

A key difference between theDataTransfer andDataTransferItem interfaces is that the former uses the synchronousgetData() method to access a drag item's data, but the latter instead uses the asynchronousgetAsString() method.

Examples

Specifications

Specification
HTML

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp