HTML5 drag and drop

Drag and drop is a common feature that drags an object and drags it to another location.

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

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

Browser support

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

Note: Safari 5.1.2 does not support dragging.

HTML5 drag and drop instance

The following example is a simple drag and drop instance:

Run the program and try to drag the picture

The program may seem a bit complicated, but we can study different parts of the drag and drop event separately.

Set elements to be draggable

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

<img draggable="true">

Drag what - ondragstart and setData()

Then, what happens when the element is dragged.

In the above example, the ondragstart property calls a function, drag, which specifies the data being dragged.

The dataTransfer.setData() method sets the data type and value of the data being dragged:

function drag(ev)

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 into other elements. If we need to set the allowed placement, we must prevent the default handling of the elements.

This is done by calling the event.preventDefault() method of the ondragover event:


Place - ondrop
The drop event occurs when the dragged data is placed.

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

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

Code explanation:

Call preventDefault() to prevent the browser from processing the default data (the default behavior of the drop event is to open as a link)

The dragged data is obtained by the dataTransfer.getData("Text") method. This method will return any data of the same type set in the setData() method.

The dragged data is the id of the dragged element ("drag1")

Append the dragged element to the drop element (the target element)


How to drag and drop an image between two <div> elements.

Try running the program

Last Updated: 2018-07-06 12:32:44 By akshay


share_facebook share_twitter share_google_plus

Please Comment Here :