Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Earning

How to Drag and Drop in HTML5?

Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180

In HTML5, drag and drop is part of the standard: Any element can be draggable.
E.g:
<head>
<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>
<body>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
</body>

To make an Element Draggable set the draggable attribute to true.
<img draggable="true">

ondragstart and setData()
Specify what should happen when the element is dragged.
ondragstart attribute calls a function, drag(event), that specifies what data to be dragged.
The dataTransfer.setData() method sets the data type and the value of the dragged data.
function drag(ev)
{
 ev.dataTransfer.setData("text", ev.target.id);
}

Where to Drop ondragover?
The ondragover event specifies where the dragged data can be dropped.
This is done by calling the event.preventDefault() method for the ondragover event.
event.preventDefault()

CONTINUE READING
Drag and Drop
HTML5
Ayesha
Tech writer at newsandstory