HTML 5 TutorialsHow to use Drag and Drop in HTML5

How to use Drag and Drop in HTML5

Drag and Drop is one of the coolest feature of HTML5 and I personally like it a lot. You will learn its use in our very simple example today. I have kept it bare minimum for the beginners to get a hang of it.

Step 1

Let us write the header first

<!DOCTYPE HTML>
<html>
<head>
<title>DRAG AND DROP DEMO </title>
<style type="text/css">
.box {width:300px
;height:300px;
border:2px solid #009933;}
</style>

We just defined the Title Drag and Drop Demo in the above code

Step 2

Let us write the Drag and Drop Script

<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");
ev.target.appendChild(document.getElementById(data));
}
</script>

</head>

We have written three main functions in the code above as follows

1. drag(ev) – It outlines the drag and is called by ondragstart to be used later. The dataTransfer.setData method sets the data type being moved. We have used Text in our example. The id is the id of the data being used.

2. allowDrop(ev) – It will be called after the drag is over. By default elements cannot be dropped so we have to override the default property. We use preventDefault() to do that.

3. drop(ev) – It is called after the actual drop. In our function above we first override the default behavior so that browser do not follow the normal function to handle the element. We then transfer the content in the variable data and then append the data with the given id in the new position.

Step 3

<body>
<p>Drag the image to the box !! </p>
<!--<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)"></div>-->

<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<br>
<img id="drag1"  src="https://blog.eduonix.com/wp-content/uploads/2012/09/HTML5_Logo_256.png" draggable="true" ondragstart="drag(event)" width="256" height="256"> 

<footer> Drag and Drop Demo </footer>
</body>
</html>

Here we calling the ondrop and ondragover methods which in turn calls the javascript method. We display a message in the footer.

Our example is now complete

Output

Before Drag

Before_DD

After Drag and Drop

AfterDD

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,223FollowersFollow
103,000SubscribersSubscribe

More article

- Advertisement -Eduonix Blog