Saturday, June 4, 2011

Drag and Drop in HTML 5

The Drag and Drop API is one of the most important parts of the HTML5 API specifications because more and more sites are using the drag and drop functionality. It talks about dragging an object in the site and dropping it anywhere. It further extends drag and drop for use between browsers and your computer which was impossible earlier (they stated security as the reason).

SOURCE:



<!DOCTYPE HTML>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type"/>
<title>Drag-n-Drop demo</title>
<style>
#mainText{color:red}
#section1, #section2, #section3 {float:left; width:165px; height:165px; padding:20px; margin:10px}
#section1 { background-color: #ff0000; }
#section2 { background-color: #00ff00; }
#section3 { background-color: #0000ff; }
#dragMe1, #dragMe2, #dragMe3 { width:100px; height:30px; padding:5px; margin:5px; }
</style>
<script type="text/javascript">
function dragStart(e) {
e.dataTransfer.effectAllowed='move';
e.dataTransfer.setData("Text", e.target.getAttribute('id'));
e.dataTransfer.setDragImage(e.target,0,0);
return true;
}
function dragEnd(e) {
e.dataTransfer.clearData("Text");
return true
}
function dragEnter(e) {
var idelt = e.dataTransfer.getData("Text");
return true;
}
function dragOver(e) {
var articleID = e.dataTransfer.getData("Text");
var sectionId = e.target.getAttribute('id');
if( articleID=="dragMe3" || sectionId == "section1" || (sectionId == "section2" && articleID == "dragMe1") ||
(sectionId == "section3" && articleID == "dragMe2") )
return false;
else
return true;
}
function dragDrop(e) {
var idelt = e.dataTransfer.getData("Text");
e.target.appendChild(document.getElementById(idelt));
e.stopPropagation();
return false;
}

</script>
</head>
<body>
<h1>Drag-n-drop Demo</h1>
<article id="mainText"> Select a text from Red section and try dropping it to Green & Blue</article>
<section id="section1" ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)" ondragover="return dragOver(event)">
<article id="dragMe1" draggable="true" ondragstart="return dragStart(event)" ondragend="return dragEnd(event)">Drag to Green</article>
<article id="dragMe2" draggable="true" ondragstart="return dragStart(event)" ondragend="return dragEnd(event)">Drag to Blue</article>
<article id="dragMe3" draggable="true" ondragstart="return dragStart(event)" ondragend="return dragEnd(event)">Drag to Any</article>
</section>
<section id="section2" dropZone="f:image/png" ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)" ondragover="return dragOver(event)"></section>
<section id="section3" ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)" ondragover="return dragOver(event)"></section>
</body></html>

No comments:

Post a Comment