Drag&Drop API
Making Elements Draggable
The drag and drop feature lets you "grab" an object and drag it to a different location.
To make an element draggable, just set the draggable attribute to true:<img draggable="true" />
Any HTML element can be draggable.
The API for HTML5 drag and drop is event-based.
Example:<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="box" ondrop="drop(event)"
ondragover="allowDrop(event)"
style="border:1px solid black;
width:200px; height:200px"></div>
<img id="image" src="sample.jpg" draggable="true"
ondragstart="drag(event)" width="150" height="50" alt="" />
</body>
</html>
What to Drag
When the element is dragged, the ondragstart attribute calls a function, drag(event), which specifies what data is to be dragged.
The dataTransfer.setData() method sets the data type and the value of the dragged data:function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
In our example, the data type is "text" and the value is the ID of the draggable element ("image").
Where to Drop
The ondragover event specifies where the dragged data can be dropped. By default, data and elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.
This is done by calling the event.preventDefault() method for the ondragover event.
Do the Drop
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute calls a function, drop(event):function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
The preventDefault() method prevents the browser's default handling of the data (default is open as link on drop).
The dragged data can be accessed with the dataTransfer.getData() method. This method will return any data that was set to the same type in the setData() method.
The dragged data is the ID of the dragged element ("image").
At the end, the dragged element is appended into the drop element, using the appendChild() function.
Basic knowledge of JavaScript is required to understand and use the API.
Comments
Post a Comment