Drag and Drop IN HTML5

In this article I describe the "Drag and Drop (DnD)" feature of HTML5. We will define in this article a draggable image that can be dropped into a rectangle.

Drag and Drop

Drag and Drop is a very common feature supported by HTML5. By doing this you can grab an object and drag it to a different position of your page. Making an object draggable is simple. Set the "draggable= true" attribute on the element you want to make moveable. You can drag anything you want.

Procedure to drag the image

Step 1

To make the element draggable, set the draggable attribute to true. 

<img draggable="true">

Step 2

Now we specify what will happen when the element is dragged. The datatransfer property is where all the DnD magic happens. It holds a piece of data sent in the drag action.

The ondragstart attribute calls a function, "drag(event)" that specifies what data to be dragged. The "dataTransfer.setData()" method set the data type and the value of the dragged data.

Step 3 

The ondragover event specifies where the dragged data can be dropped. By default, element (data) cannot be dropped in another element. To allow the drop you must prevent the default handling of the event. In case you are dragging something like a link, you need to prevent the browser default behaviour in order to navigate to the link.

Step 4

When the data that is dragged is dropped, the drop event occurs.

Browser Support

The Drag and Drop feature is supported by Internet Explorer 9, Firefox, Opera 12, Chrome and Safari 5.

This feature is not supported by Safari 5.1.2.

Coding of Drag and Drop in HTML5

<!DOCTYPE HTML>

<html>

<head>

<style type="text/css">

#div1

 {

width:400px;

height:350px;

padding:10px;

border:1px solid blue;

}

</style>

<script>

    function allowDrop(e) {

        e.preventDefault();

    }

 

    function drag(e) {

        e.dataTransfer.setData("text", e.target.id);

    }

 

    function drop(e) {

        e.preventDefault();

        var data = e.dataTransfer.getData("text");

        e.target.appendChild(document.getElementById(data));

    }

</script>

</head>

<body>

 

<p>Drag the image into the rectangle:</p>

 

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<br>

<img id="drag1" src="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" draggable="true" ondragstart="drag(event)" width="350" height="300">

 

</body>

</html>

Output

Before Drag and Drop

drag.jpg

After Drag and Drop

Drop.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all