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

XHTML

1

2

3

4

5

6

7

8

9

<!DOCTYPE HTML>

<html>

<head>

<title>DRAG AND DROP DEMO </title>

<style type="text/css">

.box {width:300px

;height:300px;

border:2pxsolid#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

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<script>

functionallowDrop(ev)

{ev.preventDefault();

}

functiondrag(ev)

{

ev.dataTransfer.setData("Text",ev.target.id);

}

functiondrop(ev)

{

ev.preventDefault();

vardata=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.