Saturday, February 11, 2012

Drag and drop in HTML 5


Drag and drop element 
 
Drag and drop is very much necessary when we want to drag some element and drop into other element. The below code will not work in opera browser.

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#mydiv {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</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>
<p>Drag the image into the rectangle:</p>
<div id="mydiv" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br />
<img id="drag1" src="yourimage.gif" draggable="true" ondragstart="drag(event)" width="400" height="100" />
</body>
</html>

Here one rectangular box will come and try to drag your picture within rectangular window. It may not work if your browser do not support HTML 5 fully.
The draggable=”true” make the image draggable.


No comments:

Post a Comment