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

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

Step 2

Let us write the Drag and Drop Script

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

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


Before Drag

After Drag and Drop