This is in continuation of the series of articles related to HTML5.
In this tutorial we will see how can we use Drag and Drop functionality of HTML5.This drag and drop functionality will allow end user to drag the content of the webpage and make the front look of the webpage according to his(end user) desire.
The following code in this tutorial consist of both some CSS and and HTML5.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#div1 {width:336px;height:70px;padding:10px;border:1px solid #aaaaaa;}
#div2 {
width: 336px;
height: 69px;
border:1px solid #aaaaaa;
-webkit-border-radius: 1050px;
-moz-border-radius: 1050px;
border-radius: 50px;
}
#div3 {
width: 100px;
height: 100px;
border:1px solid #aaaaaa;
-webkit-border-radius: 1050px;
-moz-border-radius: 1050px;
border-radius: 50px;
}
</style>
<script type="text/javascript">
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
ev.preventDefault();
}
</script>
</head>
<body>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="mountain" src="mountain.png" draggable="true" ondragstart="drag(event)" width="336" height="69" />
<img id="circle" src="Circle.png" draggable="true" ondragstart="drag(event)" />
<img id="RoundedRectangle" src="RoundedRectangle.png" draggable="true" ondragstart="drag(event)" />
</body>
</html>
CSS:
In the above code three CSS classes are used to draw a Rectangle,Circular Rectangle and a Circle.
JavaScript:
In the Javascript section we have three functions allowdrop(),drag(),drop().
On the ondragstart attribute of each image a function drag() is called which is used to define the DataType and the Value of the draggable item.
In the div tags you can see two functions are called allowdrop() and drop(). The allowdrop() function is called at the ondragover attribute of each div tag in this function ev.preventDefault(); is called which protects the default behaviour of the event to occur and the drop function is called at the ondrop attribute of each div tag which is used to get the data of the dragged item,In the above code dragged data having Id div1,div2 and div3 respectively then target.appendChild() will Append the dragged element into the drop element again ev.preventDefault() is used to protect the default event of the dragged item to occur.
In each of the image tag above you can see that it’s draggable attribute is set to true it means that this item is draggable.
For live demo click this link
Note: The default event is to open the dragged item as link.