Drag and drop is a common feature where you grab an object and drag it to another location. In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped.

A typical drag-and-drop operation looks like this: the user selects a draggable element, drags it onto a droppable element, and then releases the mouse.

Drag and drop event

During an operation, several event types are fired, and some may be fired more than once.

The event On-type event handlers Trigger point
drag ondrag Triggered when an element or selected text is dragged.
dragend ondragend Triggered when a drag action ends (such as releasing the mouse button or pressing the Esc key).
dragenter ondragenter Triggered when an element or selected text is dragged to a releasable target.
dragexit ondragexit Triggered when an element becomes no longer the selected target of a drag operation.
dragleave ondragleave Triggered when a drag element or selected text leaves a releasable target.
dragover ondragover Triggered when an element or selected text is dragged onto a releasable target (every 100 milliseconds).
dragstart ondragstart Triggered when the user starts dragging an element or selected text (see Start dragging action).
drop ondrop Emitted when an element or selected text is released on a releaseable target.

Note: Dragstart and Dragend events are not triggered when a file is dragged from the operating system into the browser.

A simple categorization of these events can be made:

  • Related to drag elements:

    • Dragstart: Drag to start

    • Drag: Dragging

    • Dragend: Drag ends

    • Drag process: dragstart*1 + drag*n + dragend*1

  • Related to releasable targets:

    • Dragenter: Drag to enter

    • Dragover: to dragover

    • Dragleave: To drag away

    • Drop: release

    • Drag process: dragenter * * n + 1 + dragover dragleave * 1 | | drop * 1

Draggable property

In HTML, elements are not draggable by default, except for images, links, and selected text that are draggable by default.

To make other HTML elements dragable, set the draggable attribute of the element you want to drag to draggable=”true”.

<p draggable="true">This text <strong>may</strong> be dragged.</p>
Copy the code

Note: When an element is made draggable, text and other child elements in the element can no longer be selected in the normal way (by mouse click and drag).

Drag and drop data

Each drag event has a dataTransfer property (a dataTransfer object) that holds the data for the event. We tend to store data when we drag and drop elements; When released to a placable target, data is read (getData). Contain any number of data items in a drag operation. Each data item is a string, a typical MIME type, such as text/ HTML.

  • DataTransfer.dropEffectGets the currently selected drag-and-drop operation type or set to a new type. Value must benone.copy.linkmove.
  • DataTransfer.effectAllowedProvides all available operation types. The valuesnone.copy.copyLink.copyMove.link.linkMove.move.all or uninitializedOne of the.
  • DataTransfer.filesContains a list of all local files available for data transfer. If the drag operation does not involve dragging a file, this property is an empty list.
  • DataTransfer.itemsRead-only provides a DataTransferItemList object that contains a list of all dragged data.
  • DataTransfer.typesRead only one format (strings array) that provides the Settings in the Dragstart event.

When a drag occurs, the data must be associated with the item being dragged. For example, when you drag selected text from a text box, the data associated with the drag data item is the text itself. Similarly, when you drag a link on a Web page, the drag data item is the URL of the link.

setData

In addition to the raw properties of the DataTransfer, we also use the setData() method to set custom drag-and-drop data items. The method takes two parameters, the data type and the data value.

const dt = event.dataTransfer;
dt.setData("application/x.bookmark", bookmarkString);
dt.setData("text/uri-list"."http://www.mozilla.org");
dt.setData("text/plain"."http://www.mozilla.org");
Copy the code

Using the getData() method, you get the data item you set.

event.dataTransfer.getData("text/plain"); // "http://www.mozilla.org"
Copy the code

clearData

This data is cleared using the clearData(type) method, which takes a parameter, the type of data to delete.

event.dataTransfer.clearData("text/uri-list");
Copy the code

If type is not specified, all types of data are deleted. If a drag contains no drag items, or all items are cleared, no drag behavior occurs.

Drag the image

When a drag occurs, a translucent image of the drag target is generated and the mouse pointer is tracked during the drag. This image is created automatically, however, you can customize the drag-and-drop feedback image using the setDragImage() method.

event.dataTransfer.setDragImage(image, xOffset, yOffset);
Copy the code
  • image: image reference. It’s usually a<img>Element, but it could be<canvas>Or any other element.
  • xOffset / yOffset: The offset of the mouse position relative to the upper left corner of the image.

An example of drawing custom drag feedback images using the IMG element:

<img src=".. /asset/03.png" alt="" id="img" />
<p id="drag" draggable="true">This text may be dragged.</p>
<script>
  document.getElementById("drag").addEventListener("dragstart".function (ev) {
    console.log("drag-start");
    let img = document.getElementById("img");
    ev.dataTransfer.setDragImage(img, 10.10);
  });
</script>
Copy the code

Drag the effect

Set the effectalhoward property in the dragstart event listener to specify which types of execution are allowed from the drag source.

ev.dataTransfer.effectAllowed = "all";
Copy the code
  • There are three basic types
    • Copy: The operation is used to indicate that the dragged data will be copied from the current position to the drop position,
    • Move: Indicates that the dragged data will be moved,
    • Link: Action indicates that some form of relationship or connection will be created between the source and the placement.
  • Combination type
    • CopyMove: Copy or move
    • CopyLink: Copy or link
    • LinkMove: links or moves
    • All: default value, copy, move, or link

The dropEffect property controls user feedback during drag-and-drop operations and affects the mouse style displayed in the browser during drag-and-drop operations. Modify the dropEffect property during a Dragenter or dragover event to none, copy, Move, or link without the above combination.

ev.dataTransfer.dropEffect = "copy";
Copy the code

In the Drop and Dragend events, you can check the dropEffect property to determine which effect was ultimately selected. If the effect selected is move, the drag data should be removed from the drag source in the Dragend event.

Place the object

When you drag an item into an HTML element, the browser does not respond by default. To make an element releasable, the element must block the default handling and set the event handling in onDragover and onDROP:

<script>
  function dragover_handler(ev) {
    // Block the default processing, indicating that placement is allowed at that location
    ev.preventDefault();
    ev.dataTransfer.dropEffect = "move";
  }
  function drop_handler(ev) {
    // Block the default processing, indicating that placement is allowed at that location
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text/plain");
    ev.target.appendChild(document.getElementById(data));
  }
</script>

<p
  id="target"
  ondrop="drop_handler(event)"
  ondragover="dragover_handler(event)"
>
  Drop Zone
</p>
Copy the code

Drag the end

When the user releases the mouse, the drag-and-drop operation ends.

The dragend event is emitted on the source element (the target element when the drag is started) regardless of whether the drag is complete or cancelled.

The dragend event handler can check the value of the dropEffect property to verify that the drag was successful. If the dropEffect property is None, drag is cancelled.

HTML 5 series

  • To understand it
  • Enhanced forms
  • Audio and Video
  • Canvas nanny tutorial (part 1) : Drawing
  • Canvas Nanny tutorial (part 2) : Animation
  • Finally drawing in SVG
  • Geolocation
  • A drag-and-drop operation
  • Understand the Web Worker
  • Understand the Web Storage
  • Understand the WebSocket