i




 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
HTML5 Drag and Drop Example
12-13-2012, 05:45 AM
Post: #1
HTML5 Drag and Drop Example
Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.

In HTML5, drag and drop is part of the standard, and any element can be draggable.

Code:
<!DOCTYPE HTML>
<html>
<head>
&lt;script&gt;
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));
}
&lt;/script>
</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>

Make an Element Draggable
Code:
<img draggable="true"&gt;

What to Drag - ondragstart and setData()
In the example above, the ondragstart attribute calls a function, drag(event), that specifies what data to be dragged.

The dataTransfer.setData() method sets the data type and the value of the dragged data:
Code:
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}

Where to Drop - ondragover
The ondragover event specifies where the dragged data can be dropped.

By default, data/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:
Code:
event.preventDefault()

Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.

In the example above, the ondrop attribute calls a function, drop(event):
Code:
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}

Summary:
1. Call preventDefault() to prevent the browser default handling of the data (default is open as link on drop)
2. Get the dragged data with the dataTransfer.getData("Text") method. This method will return any data that was set to the same type in the setData() method
3. The dragged data is the id of the dragged element ("drag1")
4. Append the dragged element into the drop element





View Asad Ali's profile on LinkedIn

Quote




User(s) browsing this thread: 1 Guest(s)