Example: Remove element by drag and drop in HTML 5

In the following example, you’ll see that how you can delete the elements with the help of drag and drop effect.

The Demo allows the user to drag an li element to another location, and drop the element over div to remove.

Demo

Drag from here

  • Item A
  • Item B
  • Item C
  • Item D
  • Item E

Drop here to remove

 
The example is using the HTML5 Drag and Drop API. To make the draggable li, we need to set the draggable attribute to true and set the element id as text data using the ondragstart event than after ondrop event of the div we get the element from the data(that we set the element id on ondragstart event of the li) and just remove the element.
from the web page.

<!DOCTYPE html>
<html>
<head>
<style> 
#maindiv{width:500px;height:300px; border:1px solid #f2f2f2;padding:10px;}
#dragdiv{width:180px;float:left;}
#dropdiv{width:250px;height:200px;float:left;
background-color:#bbb; margin-left:50px}
</style>
<script>
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
var el = document.getElementById(data);
el.parentNode.removeChild(el);
}
</script>
</head>
<body>
<div id="maindiv">
    <div id="dragdiv">
            <h3>Drag from here</h3>
        <ul id="allItems" runat="server">
            <li id="node1" draggable="true" ondragstart="drag(event)">Item A</li>
            <li id="node2" draggable="true" ondragstart="drag(event)">Item B</li>
            <li id="node3" draggable="true" ondragstart="drag(event)">Item C</li>
            <li id="node4" draggable="true" ondragstart="drag(event)">Item D</li>
            <li id="node5" draggable="true" ondragstart="drag(event)">Item E</li>  
        </ul>
    </div>
    <div id="dropdiv" ondrop="drop(event)" ondragover="allowDrop(event)">  
            <h3>Drop here to remove</h3>
    </div>
</div>
</body>
</html>