DRAG & DROP

DRAG & DROP functionality in a new feature in HTML5 and serves to move items within our website very easily.

Any element of our website can be moved.

DRAG and DROP is performed in 2 steps:

1.- Preparing the HTML element we want to move and specify what to do when you start moving.

2.- Preparing the HTML element where you can drop other things and do when released.

Explanation of step 1

Prepare the HTML element we want to move and specify that you begin to move

In our example, we have a web page with an image that we want to move and a rectangle where we put our image.

Definition of the item you want to move (our image):

<img id="dragimg1" src="dragimg1.gif" draggable="true" ondragstart="drag(event)" />

Now create a function in JavaScript, such as "drag" to define what to do when you start to move the item:

<script type="text/javascript"> function drag(ev) {   ev.dataTransfer.setData("Text",ev.target.id); } </script>

Explanation of step 2

Prepare the HTML element where you can drop other things and do when released.

In our example, we have a rectangle "rect1" where we can drop other elements.

This is the definition of our element box below:

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

Now we define the function JAVASCRIPT allowDrop drop to allow other elements here, and the drop for what to do when you release an item here:

<script type="text/javascript"> function allowDrop(ev) {   ev.preventDefault(); } function drop(ev) {   var data=ev.dataTransfer.getData("Text");   ev.target.appendChild(document.getElementById(data));   ev.preventDefault(); } </script>

Then, so will our website (dragdrop.html)

<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> function drag(ev) {   ev.dataTransfer.setData("Text",ev.target.id); } function allowDrop(ev) {   ev.preventDefault(); } function drop(ev) {   var data=ev.dataTransfer.getData("Text");   ev.target.appendChild(document.getElementById(data));   ev.preventDefault(); } </script> </head> <body> <img id="dragimg1" src="dragimg1.gif" draggable="true" ondragstart="drag(event)" /> <br/> <div id="rect1" ondragover="allowDrop(event)" ondrop="drop(event)" ></div> </body> </html>