Drag and Drop In HTML5

In this blog, we will discuss about the drag and drop property in HTML5.
For this, Follow these steps:

Step1: First we take two image controls and a paragraph tag ( which we want to drag) and a div in which we want to drop like this:
<img id="drag1" src="1.jpg" draggable="true"
ondragstart="mydrag(event)" width="60" height="70" />
<img id="drag2" src="Chrysanthemum.jpg" draggable="true"
ondragstart="mydrag1(event)" width="60" height="70" />
<p id="p1" width="15" height="70" draggable="true" ondragstart="mydrag2(event)" > Mahak Gupta</p>
<div id="div1" ondrop="mydrop(event)"
ondragover="possibleDrop(event)"></div>

Here we set the Draggable property and he events of drag and drop
Step2: Now we will write the js code and set the style of the div tag like this:

<script type="Text/javascript">
function possibleDrop(ev)
{
ev.preventDefault();
}

function mydrag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function mydrag1(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function mydrag2(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}

function mydrop(ev)
{
ev.preventDefault();
var mydata=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(mydata));
}
</script>


Here preventDefault() is used to prevent the default handling on the data. and the getData() mehod is used to return the data which is passed by setData().



The Output Will be:

124.png

Complete Program:

<html>
<head>

<script type="Text/javascript">
function possibleDrop(ev)
{
ev.preventDefault();
}

function mydrag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function mydrag1(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function mydrag2(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}

function mydrop(ev)
{
ev.preventDefault();
var mydata=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(mydata));
}
</script>
<style type="Text/css">
#div1
 {
width:500px;
height:80px;
border:1px solid Blue;}
</style>
</head>
<body>

<img id="drag1" src="1.jpg" draggable="true"
ondragstart="mydrag(event)" width="60" height="70" />
<img id="drag2" src="Chrysanthemum.jpg" draggable="true"
ondragstart="mydrag1(event)" width="60" height="70" />
<p id="p1" width="15" height="70" draggable="true" ondragstart="mydrag2(event)" > Mahak Gupta</p>
<div id="div1" ondrop="mydrop(event)"
ondragover="possibleDrop(event)"></div>

</body>
</html>


Ebook Download
View all
Learn
View all