HTML5 drag and drop example
We at Taiijas Infotech are constantly experimenting, researching and implementing inhouse. This is a small example which can be built in 20mins explaining how the drag and drop works in HTML5.
Given below is an example of the drag and drop which can be very easily implemented using HTML5’s new attributes. The attributes used here are
draggableNew | true, false, auto | Specifies whether or not a user is allowed to drag an element |
dropzoneNew | copy, move, link | Specifies what happens when dragged items/data is dropped in the element |
The codes for pages that are needed are:
1. dragdemo.html
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>HTML5 Drag & Drop Demo</title>
<link rel=”stylesheet” href=”html5simple.css” type=”text/css” />
<!–[if lt IE 9]>
<script src=”html5.js”></script>
<![endif]–>
<script>
function DragHandler(target, e) {
e.dataTransfer.setData(‘Text’, target.id);
}
function DropHandler(target, e) {
var id = e.dataTransfer.getData(‘Text’);
target.appendChild(document.getElementById(id));
e.preventDefault();
}
</script>
</head>
<body>
<div id=”dndcontainer”>
<div ondrop=”DropHandler(this, event)” ondragenter=”return false” ondragover=”return false”>
<img src=”item-1.png” id=”club” ondragstart=”DragHandler(this, event)” width=”75″ height=”75″ border=”0″ alt=”” />
<img src=”item-2.png” id=”heart” ondragstart=”DragHandler(this, event)” width=”75″ height=”75″ border=”0″ alt=”” />
<img src=”item-3.png” id=”spade” ondragstart=”DragHandler(this, event)” width=”75″ height=”75″ border=”0″ alt=”” />
<img src=”item-4.png” id=”diamond” ondragstart=”DragHandler(this, event)” width=”75″ height=”75″ border=”0″ alt=”” />
</div>
<div ondrop=”DropHandler(this, event)” ondragenter=”return false” ondragover=”return false”></div>
<div id=”demonotes”>Drag and drop images from one container to another. Works in all major browsers except Opera.</div>
</div>
</body>
</html>
2.CSS file: html5simple.css
body {
width:450px;
margin: 0px auto;
font-family: Arial, Helvetica, sans-serif;
color:#666;
}
#dndcontainer {
margin:20px auto;
padding:20px;
width:410px;
clear:both;
}
.dndbox {
border:2px #ccc solid;
padding:10px;
margin:10px;
float:left;
width:160px;
height:200px;
}