Drag and Drop
Drag and drop is known to be a very common feature. It happens when you are "grabbing" an object and dragging it to a someother location.
In the latest HTML5, drag and drop is included, and any element is draggable.
The table numbers specifies the first browser version which fully supported Drag and Drop.
|Drag and Drop||4.0||9.0||3.5||6.0||12.0|
HTML Drag and Drop Example
The example given below illustrates a simple drag and drop scenario:
It may look complicated, but after going through all the parts of a drag and drop event we can understand it clearly.
Make an Element Draggable
First: For making an element draggable, you need to change the draggable attribute to true:
What to Drag - ondragstart and setData()
Later,you need to specify what should be happening if the element is dragged.
In the example given above, the ondragstart attribute is calling a function, drag(event), which is specifying what data should be dragged.
The dataTransfer.setData() method is setting the data type and the value of the dragged data:
Here, the data type is given as "text" and the value given is the draggable element id ("drag1").
Where to Drop - ondragover
The ondragover event is used to specify where the dragged data should be dropped.
With default settings, data/elements is not possible to be dropped in some other elements. For allowing a drop, we must be preventing the default handling of the element.
This can be done by calling the event.preventDefault() method for the ondragover event:
Do the Drop - ondrop
When the dragged data is getting dropped, a drop event is occuring.
In the above example, the ondrop attribute is calling a function, drop(event):