HTML drag and drop

HTML supports drag and drop feature which allows users to drag an element and drop it on another location. This feature was included in HTML 5.

HTML drag and drop

HTML 5 supports drag and drop feature which allows users to drag an element and drop it on another location.

Creating a drag and drop

  • To make an element draggable, you should first set the draggable attribute.
<button id="dragbtn" draggable="true" ondragstart="dragStart(event)">Drag Me</button>
  • Specify a global ondragstart() event handler.
<script>
function dragStart(ev) 
{
    ev.dataTransfer.setData("text", ev.target.id);
}
</script>
  • Create a drop zone and ondrop() event handler.
<script>
function dragEnd(ev) 
{
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
<div id="dropzone" ondrop="dragEnd(event)" ondragover="dragOver(event)" style="height:100px; border:1px solid red;"></div>
  • Create an ondragover() event handler.
function dragOver(ev) 
{
    ev.preventDefault();
}

Complete code

<!DOCTYPE html>
<html>
<head>
<script>
function dragOver(ev) {
    ev.preventDefault();
}

function dragStart(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function dragEnd(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="dropzone" ondrop="dragEnd(event)" ondragover="dragOver(event)" style="height:100px; border:1px solid red;"></div>

<button id="dragbtn" draggable="true" ondragstart="dragStart(event)">Drag Me</button>

</body>
</html>

Output

Note: Drag and drop feature is not supported by all browsers. I recommend using Google Chrome.


Share Tweet Send
0 Comments
Loading...