Have you ever seen those famous drag and drop uploading features on the websites? Yes, I am talking about the ones seen on dropbox and the latest example Facebook. The new feature is courtesy HTML5, which although will be officially released this year; but has gained a lot of attention. You might think that even the basic version of the drag and drop feature would be hard to understand, that is not the case. So, for all those who want to integrate that feature in their website, here is a step by step guide on how to apply it:

HTML 5 Drag and drop Instructions

Lets take the procedure step by step, as we know that the only script you need to initialize HTML5 is the tag

<!DOCTYPE HTML>

add that at the start of the document and you are good to go, continue with the rest of the code:

<!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="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>

HTML 5 drag and drop explanation

We begin by creating two three functions in the <head> tag, these are simple jscript functions and will be invoked by the item you want to drop. You can use these as they are, but be careful of the variable names when you use them.

Making an element dragable

Not all information can be dragged or dropped. in the body tag you will notice an extra attribute in the image tag.

<img id=”drag1” draggable=”true”>

 

This attribute will enable that feature.

What should be dragged

The next thing is what should be dragged. Once the element is clicked on, we will invoke the function drag(), giving it the ID of the image/text we want to move.

function drag(ev)


{
ev.dataTransfer.setData("Text",ev.target.id);
}

in the case mentioned above, the “Text” is dragged with ID “drag1”.

Where to drop

by default the libraries dont allow the feature to drop an element on top of another, so we invoke allowdrop to overwrite it.

Perform the drop action

Last but not least the drop function, this is catered by

function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}

Once themouse button is released or the image is over the other container then the function will be invoked. the var data retrieves the information from the first container and store it in the target.appendChild and replaces it’s content.

The code is pretty straight forward and you can use it to save files – try it if you may, and share you experience with us.