...

/

Drag & Drop API Hands-On

Drag & Drop API Hands-On

In this lesson, we will learn how to make use of the drag and drop API to allow users to move objects on a web page and place them within a set position. Let's begin!


Challenge: Drag the logo


In this challenge, you are required to make use of the drag and drop API to allow the user to drag the Educative logo and drop it in the rectangle space provided. A demo of the final result is provided below:


Implement your solution below


  • HTML
html

Solution review


<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
// Set the drag's format and data. Use the event target's id for the data
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
// Get the data, which is the id of the drop target
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
// Clear the drag data cache (for all formats/types)
ev.dataTransfer.clearData();
}
</script>
</head>
<body>
<h2>Educative: Drag and Drop API Exercise </h2>
<p>Drag the Educative logo image into the rectangle below:</p>
<div id="rect" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<blockquote> Educative Logo </blockquote>
<img id="drag_logo" src="https://cdn-images-1.medium.com/max/1200/1*dMSWcBZCuzyRDeMr4uE_og.png" draggable="true" ondragstart="drag(event)" width="340" height="235">
</body>
</html>

First of all: To make an element draggable, set the draggable attribute to true:

      <img id="drag_logo" src="" draggable="true" ondragstart="drag(event)">

In the example above, the 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:

 ...