Drag and Drop

HTML5 introduces a new feature, called drag and drop, in Web pages. The drag and drop feature allows you to drag a textual data or an image from the source area to target on a Web page, where source and target area can be two containers or text areas. You can perform drag and drop operation by creating a drag data store, which specifies the data that is used for drag and drop operation. It contains a drag data store item list, which is a list of items representing the dragged data, such as text or files. You can create a draggable element by using the draggable attribute and the dragstart event to store the data that has to be dragged. The event handler checks whether the selected text is draggable or not and store the data in the DataTransfer object.

The DragEvent interface is used to create objects of the DataTransfer interface and initialize the dragging operation. It provides the dataTransfer attribute and initDragEvent() method for this purpose. The dataTransfer attribute of the DragEvent interface returns an object of the DataTransfer interface. The initDragEvent() method initializes an event to drag the data.

You can make a draggable HTML element by using the draggable attribute. The syntax to use the draggable attribute is given as follows:

element . draggable [ = value ]

In the preceding syntax, the value can be true, false, or auto. The true value indicates that the element is draggable; the false value indicates that the element is not draggable; and the auto value specifies the default behavior of the element.

The following code snippet shows an example of using the draggable attribute:

< BODY > < p draggable="true" > You can drag this paragraph </p > < p draggable="false" > You cannot drag this paragraph < /p > < /BODY >

The HTML elements may specify the dropzone attribute to drop the data. This attribute is specified by using any one of the following values:

  • copy: Creates a copy of the draggable data from source location to a target location
  • move: Moves the draggable data from the source location and place it to a target location
  • link: Creates a link of the draggable data from source location to a target location

Click here for demos to see how to implement drag and drop feature:
demo