THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

HTML5 Drag and Drop


Drag and drop is a piece of the HTML5 standard.


welookups

Drag the welookups picture into the rectangle.


Drag and Drop

Drag and drop is a most valuable component in website page.

In HTML5 intuitive is normal piece of the component can be draggable.


Browser Support

The numbers in the table determine the primary program form that completely bolsters Drag and Drop.

API
Drag and Drop 4.0 9.0 3.5 6.0 12.0

HTML Drag and Drop Example

The precedent underneath is a basic intuitive example:

Example

<!DOCTYPE HTML>
<html>
<head>
<script>
work allowDrop(ev) {
    ev.preventDefault();
}

work drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

work drop(ev) {
    ev.preventDefault();
    var information = 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>
Try it yourself »

We are beginning investigation parts of a simplified occasion.


Make an Element Draggable

First of all To make a component draggable set the draggable credit to true

<img draggable="true">

What to Drag - ondragstart and setData()

Then, determine what ought to happen when the component is dragged.

In the precedent over, the ondragstart property calls a capacity, drag(event), that determines what information to be dragged.

The dataTransfer.setData() strategy sets the information type and the estimation of the hauled data:

work drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

The information type is "text" and the esteem is the id of the draggable component ("drag1").


Where to Drop - ondragover

The ondragover occasion determines where the hauled information can be dropped.

information/components can't be dropped in different components. To permit a drop, we should keep the default treatment of the element.

This is finished by calling the event.preventDefault() strategy for the ondragover event:

event.preventDefault()

Do the Drop - ondrop

When the hauled information is dropped, a drop occasion occurs.

In the model over the ondrop trait calls a capacity drop:

work drop(ev) {
    ev.preventDefault();
    var information = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}

Code explained:

  • Call preventDefault() to keep the program is open as connection on drop.
  • Get the hauled information with the dataTransfer.getData() strategy. This strategy will restore any information that was set to a similar kind in the setData() method
  • The hauled information is the id of the hauled component ("drag1")
  • It is affix the hauled component into the drop element.