HTML Drag & Drop


Drag and Drop (DnD) is a powerful User Interface concept that allows you to easily copy, reorder, and delete objects with just a few mouse clicks. This allows the user to click and hold the mouse button over an element, drag it to a new position, and then release the mouse button to drop it there.

Developers will have to use advanced JavaScript programming or other JavaScript frameworks like jQuery to achieve drag and drop functionality with traditional HTML4.

Now, HTML 5 has a Drag and Drop (DnD) API that adds native DnD support to the browser, making coding much easier.

All major browsers, including Chrome, support HTML 5 DnD.


Events of Drag & Drop


Several events are caused at different points during the drag and drop process. These occasions are mentioned below.


Sr. No.Events & Description
1dragstart
When the user drags the object, this event is triggered.
2dragenter
When the mouse is first pushed over the target element during a drag, this event is activated. This event's listener should indicate whether or not a drop is permitted over this spot. A drop is not permitted by default if there are no listeners or if the listeners do not perform any operations.
3dragover
When the mouse is passed over an element during a drag, this event is activated. The procedure performed during a listener is frequently the same as the dragenter case. .
4dragleave
When the mouse leaves an element while dragging, this event is triggered. All highlighting or insertion markers used for drop input should be removed by listeners.
5drag
When the mouse is pushed while dragging an object, this event is triggered.
6drop
At the end of the drag process, the drop event is fired on the element where the drop occurred. The data being dragged will be retrieved by a listener and inserted into the drop spot.
7dragend
When the user lets go of the mouse button when dragging an object, this event is triggered.


DataTransfer Object


For all drag and drop cases, the event listener methods accept an Event object with a readonly attribute called dataTransfer.


As follows, dataTransfer returns a DataTransfer object associated with the event:


function EnterHandler(event) {
  DataTransfer dt = event.dataTransfer;
  //Code goes here
}



Data about the drag-and-drop operation is stored in the DataTransfer object. This data can be extracted and set using the DataTransfer object's various attributes.