This site is mobile accessible. Press the "Tap Here" button to use a smaller font-size.
Smartphone icons created by Freepik - Flaticon
In HTML, any element can be dragged and dropped.
Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.
The numbers in the table specify the first browser version that fully supports Drag and Drop.
API | |||||
---|---|---|---|---|---|
Drag 'n' Drop | 4.0 | 9.0 | 3.5 | 6.0 | 12.0 |
The example below is a simple drag and drop example:
<!DOCTYPE HTML> <html> <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> </html>
It might seem complicated, but lets go through all the different parts of a drag and drop event.
First of all: To make an element draggable, set the draggable attribute to true:
<img draggable="true">
The
method sets the data type and the value of the dragged data:function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); }
In this case, the data type is "text" and the value is the id of the draggable element ("drag1").
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute calls a function, drop(event):
function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); }
Code explained:
How to drag (and drop) an image back and forth between two <div> elements:
<style> #div1, #div2 { float: left; width: 100px; height: 35px; margin: 10px; padding: 10px; border: 1px solid black; } </style> <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> <p>Drag the image back and forth between the two div elements.</p> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> <img src="include/images/img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31"> </div> <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">/div>