HTML 5 comes with a very nice Drag and Drop JavaScript API that brings native Drag and Drop support to the browser. This makes coding DnD much easier. The specification defines an event based mechanism (dependent on JavaScript and markup) for declaring that most HTML elements be draggable on a page.

This native support results in faster, more responsive web apps. To achieve drag and drop functionality with the HTML 4 standard, web developers would have to use complex JavaScript programming or integrate other JavaScript frameworks such as jQuery.

Browser Support

Most modern browsers support Drag and Drop. Internet Explorer 9, Firefox, Opera 12, Chrome, and Safari 5 support drag and drop. Early versions of Internet Explorer do not support HTML5 Drag and Drop.

Making an Element Draggable

To make an element draggable, you simply need to set the draggable attribute to true.

Example

Here is an example, where you can drag an image into a div element.

Drag the crumpled paper into the trash can.

Aside from the Drag and Drop events, we also leverage the DataTransfer object, which is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types.

Drag and Drop Operations

In the example above, the ondragstart attribute calls a function drag(event) that specifies what data is to be dragged. The dataTransfer.setData() method sets the data type and the value of the dragged data. The ondragover event specifies where the dragged data can be dropped.

By default, data and/or elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element. This is accomplished by calling the event.preventDefault() method for the ondragover event. When the dragged data is dropped, a drop event occurs. In the example above, the ondrop attribute calls a function, drop(event).

Listening for Drag and Drop Events

In this tutorial, we used the DataTransfer object to help us with the Drag and Drop operations. There are 7 events that can be used to monitor the entire Drag and Drop process.

For example…