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

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

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

Step 2

Let us write the Drag and Drop Script

function allowDrop(ev)

function drag(ev)

function drop(ev)
var data=ev.dataTransfer.getData("Text");;


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

<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>
<img id="drag1"  src="" draggable="true" ondragstart="drag(event)" width="256" height="256"> 

<footer> Drag and Drop Demo </footer>

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


Exclusive content

- Advertisement -

Latest article


More article

- Advertisement -Eduonix Blog