Detailed and Example of HTML5 Drag and Drop

Keywords: Front-end Attribute Firefox html5 Javascript

brief introduction

Drag-and-drop is a common feature, which is to drag an object to another location after grabbing it.

In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped.

First click on a small example: execute JavaScript when the user starts dragging < p > elements

<p draggable="true" ondragstart="myFunction(event)">Drag me!</p>

Tip: Links and images are draggable by default, without draggable attributes.

Definition and Usage

During drag-and-drop, the following events are triggered:

  • Trigger an event (source element) on the drag target:

    • ondragstart - triggered when the user starts dragging elements

    • ondrag - triggered when the element is dragging

    • ondragend - Triggered after the user has dragged the element

  • Events triggered when the target is released:

    • ondragenter - Triggers this event when an object dragged by the mouse enters its container

    • ondragover - triggers this event when a dragged object is dragged within the scope of another object container

    • ondragleave - triggers this event when the object being dragged by the mouse leaves its container range

    • ondrop - triggers this event when the mouse button is released during a drag

Browser support

Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support dragging.

Note: Safari 5.1.2 does not support dragging; when dragging elements, ondragover events are triggered every 350 milliseconds.

Example

First paste the code, then explain it one by one:

<!DOCTYPE html>
<html>
<head>
<title>HTML5 Drag and drop</title>
<meta charset="utf-8">
<style>
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>
</head>
<body>
<p>drag img_w3slogo.gif Pictures in rectangular boxes:</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="images/img_w3slogo.gif" draggable="true" ondragstart="drag(event)" width="300" height="56">

<script>
function allowDrop(ev){
    ev.preventDefault();
}

function drag(ev){
    ev.dataTransfer.setData("Text",ev.target.id);
}

function drop(ev){
    ev.preventDefault();
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

</script>
</body>
</html>

The page effect before dragging is as follows:

The following is to parse the meaning of the above code.

Settings elements can be dragged and dropped

First, to make the element draggable, set the draggable attribute to true:

<img draggable="true">

Drag what - ondragstart and setData()

Then, specify what happens when the element is dragged.
In the example above, the ondragstart attribute calls a function, drag(event), which specifies the data to be dragged.
The dataTransfer.setData() method sets the data type and value of the dragged data:

function drag(ev){
    ev.dataTransfer.setData("Text",ev.target.id);
} 

In this example, the data type is "Text" and the value is the ID of the draggable element ("drag1").

Where to put it - ondragover

The ondragover event specifies where to place the dragged data.
By default, data/elements cannot be placed in other elements. If you need to set permissible placement, we must prevent default processing of elements.
This is done by calling the event.preventDefault() method of the ondragover event:

event.preventDefault()

Place - ondrop

drop events occur when dragged data is placed.
In the example above, the ondrop attribute calls a function, drop(event):

function drop(ev){
    ev.preventDefault();
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

Code Interpretation:

  • Call preventDefault() to avoid default processing of data by browsers (the default behavior of drop events is to open as links)

  • The dragged data is obtained by the dataTransfer.getData("Text") method. This method returns any data set to the same type in the setData() method.

  • The dragged data is the ID of the dragged element ("drag1")

  • Append the dragged element to the placement element (target element)

The results are as follows:

dataTransfer object

In the process of dragging operation, we can use the dataTransfer object to transfer data so that we can perform other operations on the data at the end of the dragging operation.

Object properties:

  • dropEffect: Sets or returns the allowed drag-and-drop behavior on the drag-and-drop target. If the drag-and-drop behavior set here is no longer within the multiple drag-and-drop behavior set by the effectAllowed property, the drag-and-drop operation will fail. This attribute value is only allowed to be one of the four values of "null", "copy", "link" and "move".

  • effectAllowed: Sets or returns the drag behavior allowed by the dragged element. The attribute values can be set to none, copy, copyLink, copyMove, link, linkMove, move, all and uninitialized.

  • items: This property returns the DataTransferItems object, which represents the drag data.

  • Type: This property returns a DOMStringList object that includes all types of data stored in the dataTransfer.

Object method:

  • setData(format,data): assigns data in a specified format to the dataTransfer object. The parameter format defines the format of the data, that is, the type of the data, and the data is the data to be assigned.

  • getData(format): Get data in the specified format from the dataTransfer object, format represents the data format, and data is the data.

  • clearData([format]): Delete data in the specified format from the dataTransfer object with optional parameters, or delete all data in the object if it is not given.

  • AddElement: Add custom icons

  • setDragImage(element,x,y): Set custom icons for drag-and-drop operations. Among them, element sets the custom icon, x sets the distance between icon and mouse in horizontal direction, and Y sets the distance between icon and mouse in vertical direction.

Identify what is draggable

function dragstart_handler(ev) {
 console.log("dragStart");
 // Add the target element's id to the data transfer object
 ev.dataTransfer.setData("text/plain", ev.target.id);
}

<body>
 <p id="p1" draggable="true" ondragstart="dragstart_handler(event);">This element is draggable.</p>
</body>

Define the drag's data

function dragstart_handler(ev) {
  // Add the drag data
  ev.dataTransfer.setData("text/plain", ev.target.id);
  ev.dataTransfer.setData("text/html", "<p>Example paragraph</p>");
  ev.dataTransfer.setData("text/uri-list", "http://developer.mozilla.org");
}

Define the drag image

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

Define the drag effect

function dragstart_handler(ev) {
  // Set the drag effect to copy
  ev.dataTransfer.dropEffect = "copy";
}

Define a drop zone

function dragover_handler(ev) {
 ev.preventDefault();
 // Set the dropEffect to move
 ev.dataTransfer.dropEffect = "move"
}
function drop_handler(ev) {
 ev.preventDefault();
 // Get the id of the target and add the moved element to the target's DOM
 var data = ev.dataTransfer.getData("text");
 ev.target.appendChild(document.getElementById(data));
}
<body>
 <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
</body>

Drag and Drop Problem in Firefox Browser

But here we find a problem in Firefox browser:
HTML 5 drag and drop, using preventDefault to prevent new pages from popping up, but it doesn't work under Firefox?
Solution:

document.body.ondrop = function (event) {
    event.preventDefault();
    event.stopPropagation();
} 

Or for the example above, it is possible to add it to ondrop method:

function drop(ev){
    ev.preventDefault();
    ev.stopPropagation();
    var data=ev.dataTransfer.getData("Text");
    console.log(ev.target);
    ev.target.appendChild(document.getElementById(data));
}

Reference resources

HTML Drag and Drop API
DataTransfer

Posted by BinaryDragon on Fri, 07 Jun 2019 15:49:50 -0700