Drag and drop is a widely used feature where you grab an object and move it to another location on the screen.
The numbers in the table indicate the earliest browser version that fully supports Drag and Drop.
Here’s a straightforward example of drag and drop:
<!DOCTYPE HTML> <html> <head> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { function drop(ev) { </head> <body> <div id=”div1″ ondrop=”drop(event)” ondragover=”allowDrop(event)”></div> <img id=”drag1″ src=”img_logo.gif” draggable=”true” ondragstart=”drag(event)” width=”336″ height=”69″> </body> </html> |
While it might appear complex, let’s break down the various components of a drag and drop event.
Firstly, to enable an element to be draggable, set the draggable attribute to true:
<img draggable=“true”> |
Next, define what action should occur when the element is being dragged.
In the example above, the ondragstart
attribute invokes a function, drag(event)
, which determines the data to be dragged.
Using dataTransfer.setData()
method establishes both the data type and the value of the data being dragged.
function drag(ev) { ev.dataTransfer.setData(“text”, ev.target.id); } |
In this instance, the data type is set to “text” and the value is the id of the draggable element (“drag1”).
The ondragover event dictates where the dragged data can be dropped.
By default, elements do not accept drops from other elements. To enable dropping, we need to prevent the default behavior of the element.
This is achieved by invoking the event.preventDefault() method within the ondragover event handler:
event.preventDefault() |
When the dragged data is dropped, a drop event is triggered.
In the example provided, the ondrop attribute invokes a function named drop(event):
function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData(“text”); ev.target.appendChild(document.getElementById(data)); } |
Here’s the code explained:
preventDefault()
to stop the browser from handling the data with its default action (typically opening as a link on drop).dataTransfer.getData()
method, which returns data set with the same type in the setData()
method.