To implement drag and drop functionality, there need to be two HTML elements each with at least one role: draggable and drop zone. The draggable element is the element that can be dragged around and dropped somewhere. The drop zone is the element on which the draggable element is dropped. Each element can take more than one role and more than element can take the same role.
Drag and Drop Events
dragstart: This event gets fired when the user starts dragging the object.
dragend: This event gets fired when the drag is over and the user releases the mouse button.
dragenter: This event gets fired when the mouse is first moved over the drop zone.
dragover: This event keeps on firing as long as the draggable element is being dragged over the drop zone.
dragleave: This event gets fired when the user drags the draggable object out of the drop target.
drop: This event is fired when the user drops the draggable object on the drop zone.
The dragstart and dragend are event listeners for the draggable element and dragenter, dragover, dragleave and drop are event listeners for the drop zone.
All the event listener methods we have already discussed accept Event object. This object has only a readonly attribute named dataTransfer and it returns a DataTransfer object. This object holds data about the drag and drop operation. Different DataTransfer attributes are:
dropEffect: To get or set the kind of operation that is currently selected
effectAllowed: To get or set the kind of operations that are allowed
setData: To set the specified data. format: setData(format, data)
getData: To get the specified data. format: getData(format)
Drag and Drop Implementation
To implement drag and drop functionality, you first have to make an element draggable by setting the value of draggable attribute to true. Then you need to attach different event listeners to allow dropping. On the dragstart, you can specify what data to be dragged. You can use the dataTransfer.setData() method to set the data type and the value of the dragged data.
To accept a drop, the drop zone needs to listen to at least two events: dragover and drop. On the dragover, you can specify where the dragged data can be dropped. By default, elements are not allowed to be dropped in other elements. So in order to allow a drop, we must prevent the default handling of the element by calling the event.preventDefault() method for the ondragover event.
On the drop, you can get the dragged data using dataTransfer.getData() method and then append the dragged element into the drop zone. You also have to prevent the default handling as default is opening as a link on drop.