Latest web development tutorials

HTML5 Drag and Drop

Drag and drop (Drag and drop) is part of the HTML5 standard.

W3cschool icon and drag it to the rectangle.

Drag and Drop

Drag and drop is a common feature, that is to crawl onto another location after the object.

In HTML5, drag and drop is a standard part of any element can drag and drop.

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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

Note: Safari 5.1.2 does not support drag.

HTML5 Drag and Drop Examples

The following example is a simple drag and drop Example:


<meta charset="utf-8">
<style type="text/css">
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
function allowDrop(ev)

function drag(ev)

function drop(ev)
    var data=ev.dataTransfer.getData("Text");;

<p>拖动 图片到矩形框中:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="/images/logo.png" draggable="true" ondragstart="drag(event)" width="336" height="69">


try it"

It may seem a little complicated, but we were able to study different parts of the drag and drop events.

Element is set to drop

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

<img draggable="true">

Drag What - ondragstart and setData ()

Then, when the element is dragged provision, what will happen.

In the above example, ondragstart attribute calls a function, drag (event), which defines the data being dragged.

dataTransfer.setData () method to set the data type and value towed data:

function drag(ev)

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

Where to put - ondragover

ondragover event specified where to place the data being dragged.

By default, you can not place the data / elements into other elements. If you need to set up allows you to place, we must prevent the default handling of the element.

Do this by calling ondragover event event.preventDefault () method:


Be placed - ondrop

When placed dragged data, drop event occurs.

In the above example, ondrop attribute calls a function, drop (event):

function drop(ev)
    var data=ev.dataTransfer.getData("Text");;

Code explanation:

  • Call the preventDefault () to prevent the default browser for data processing (drop event's default behavior is to open a link)
  • Get dragged data through dataTransfer.getData ( "Text") method. This method will return the same data set of any type in setData () method.
  • Data is towed towed element id ( "drag1")
  • The dragged element appended to place elements (target element) in


More examples

Drag and drop the image back and forth
How to drag and drop images between two <div> elements.