The complete example to remove element from the list by drag and drop in HTML 5

In the following example, you’ll learn that how can you delete the elements with the help of drag and drop effect in HTML5 and JavaScript. Drag and drop is a very common feature in HTML5.

The Demo allows the user to drag an element (‘li’ HTML tag) from the list and drop the element over right side area (‘div’ HTML element) to remove element from list.

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. First create a list of some elements using ‘li’ html elements with the ‘draggable’ attribute to ‘true’ value. The ‘draggable’ attribute of an any element specifies whether an element is draggable or not. The ‘true’ value Specifies that the ‘li’ element is draggable. We also define the ‘ondragstart’ event for all ‘li’ elements, the ‘ondragstart’ event occurs when the user starts to drag an element.

On the drag event we set the element id as text data. And when user drop an element on right side ‘div’ container, we find the dropped element on the basis of element’s id (which we set on drag event of the li) using ‘ondrop; event and just remove the element.
The ‘ondrop’ event occurs when the dragged element is dropped on the drop target.

<!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>