Using HTML5 to Add Drag-and-Drop Content to Your Webpage
<!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.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





