HTML Drag and Drop
In HTML, you can drag and drop any element.
Drag and Drop
Drag and drop is a widely used function. It involves picking up an item and moving it to another place.
HTML Drag and Drop Example
Here's a basic drag and drop demonstration below:
It might appear complex, but let's break down the various components of a drag and drop event.
Make an Element Draggable
Firstly, to enable an element to be dragged, just set the draggable
attribute to true:
What to Drag - ondragstart and setData()
Next, define the behavior when the element is dragged.
In the given example, the ondragstart
attribute triggers a function called drag(event). This function decides what information should be moved when dragging.
The dataTransfer.setData()
function establishes both the type of data and its value for the data being dragged.
ev.dataTransfer.setData("text", ev.target.id);
}
Here, the data type is "text," and the value represents the identification (ID) of the element that can be dragged("drag1").
Where to Drop - ondragover
The ondragover
event tells us where we're allowed to drop the dragged data.
Normally, you can't put things inside other things on a web page. But if you want to let that happen, you have to stop the usual way the thing behaves.
To achieve this, you use the event. event.preventDefault()
method for the ondragover event.
Do the Drop - ondrop
When you release the data you were dragging, a drop event happens.
In the given example, the ondrop attribute triggers a function named drop(event).
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Code explained:
- To stop the browser's usual action of treating the data as a link and opening it when dropped, just use preventDefault().
- To retrieve the data that's been dragged, you can use the dataTransfer.getData() method. It gives you back the data you previously set using the setData() method, as long as the data type matches.
- The data being dragged is the identification (ID) of the dragged item, which in this case is "drag1".
- Add the dragged item to the drop area.