Thursday, July 4, 2013

HTML 5 Drag - Drop Example

HTML 5 supports drag and drop. It is not difficult to implement that. Following example will teach you how to do it.
1. Create a new html page and add a DIV and a BUTTON as below.
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script>

  </script>
</head>

<body>
    <div style="border:solid 1px red;width:200px;height:75px;"></div>
    <input type="button" name="btn1" value="Drag me"/>
</body>
</html>

2. Save the file and open it in a web browser. Output will be as below.
 Now we are going to let the user to drag the BUTTON and put it in to the DIV.

In order to do this
    ① We should set the 'draggable' attribute of BUTTON to true.
    ② The 'ondragstart' event of the BUTTON should be handled.
<input draggable="true" ondragstart="startDrag(event)" type="button" name="btn1" value="Drag me"/>
  
  ③ The 'ondragover' event of the DIV should be handled.
  ④ The 'ondrop' event of the DIV should be handled.
<div ondrop="drop(event)" ondragover="dragOver(event)" style="border:solid 1px red;width:200px;height:75px;"></div>

Now we should define the startDrag(), drop() and dragOver() methods within the <script></script> tags.

3. In startDrag() we just store the id of the BUTTON in 'dataTransfer' object. 
function startDrag(evt) {
  evt.dataTransfer.setData("btnId", evt.target.id);
}

4. The default behaviour of HTML elements do not allow to drop on them. So when dragging over the DIV we have to avoid this default behaviour. So our dragOver() method should be as below.
function dragOver(evt) {
  evt.preventDefault();//Preventing default undroppable behaviour
}

5. Finally our drop method should be as below.
function drop(evt) {
  evt.preventDefault();//Preventing default undroppable behaviour
  var id = evt.dataTransfer.getData("btnId");//Retrieving previously stored id.
  evt.target.appendChild(document.getElementById(id));//Appending BUTTON as a child of the DIV
}

6. Finally out HTML page will looks like below.
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script>
    function startDrag(evt) {
      evt.dataTransfer.setData("btnId", evt.target.id);
    }
    function dragOver(evt) {
      evt.preventDefault();
    }
    function drop(evt) {
      evt.preventDefault();
      var id = evt.dataTransfer.getData("btnId");
      evt.target.appendChild(document.getElementById(id));
    }
  </script>
</head>

<body>
    <div ondrop="drop(event)" ondragover="dragOver(event)" style="border:solid 1px red;width:200px;height:75px;"></div>
    <input draggable="true" ondragstart="startDrag(event)" type="button" id="btn1" value="Drag me"/>
</body>
</html>

7. Now try to drag and drop the button in to the DIV. It will work.

No comments:

Post a Comment