The term Drag-and-Drop refers to the action of moving items using the mouse. Most often, this action is associated with moving files into folders.
The ability to drag and drop blocks and elements from one section to another makes website builders like Tilda and Wix so convenient. These platforms allow users to create pages without any programming knowledge. The easy-to-use interface makes it possible to build a landing page in just a couple of hours. Today, we will show you how to create similar draggable elements.
The first thing to note is that we will implement the drag-and-drop functionality without loading any frameworks or JavaScript libraries. For the desired result, knowledge of the browser API and support for the following versions is enough: Firefox 3.5+, Chrome 4, 9+, Safari 6+, Opera 12+.
Before writing the code, we must address two tasks:
Determine what and where we are dragging (draggable element and dropzone).
Decide what will happen to the dragged element once it is dropped.
As usual, events are triggered in the browser when the specified conditions are met. Now, let's take a closer look at the events that occur until the object reaches the target area.
When dragging elements, seven events are triggered. Even though their functions are intuitive, it's important to understand the circumstances under which they are triggered.
This list of events is divided into two subgroups. Events #1, #5, and #7 apply to the dragged element, while the others are used for the target area. The events do not function the other way around and cannot occur simultaneously. Therefore, you need to determine what will happen on the screen when your element is dragged into the dropzone.
Now, let's get to the practical implementation.
Draggable elements can be blocks, images, or text. We’ll provide an example using a to-do list, where the draggable element will be labeled “TASK,” and the target area will be labeled “DONE.” There will be two <div>
elements in the HTML markup since one is the draggable element and the other is the drop zone. You can create as many elements and drop zones as needed.
Create an HTML file in the new project directory and place the basic code for a web page into it. Also, create a .css
and .js
files in the same folder. To ensure the styles are applied, include the link to the style.css
file between the <head>
tags and the link to script.js
just before the closing <body>
tag.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Example to Perform Drag and Drop</title>
<link rel="stylesheet" href=" css/ style.css" />
</head>
<body>
<script src="script.js"></script>
</body>
</html>
Now, you need to create the draggable element and the target zone. As mentioned earlier, place the draggable element called "TASK" and the drop zone (where it will be dropped) between the <body>
tags. Also, make sure to enable element dragging by setting the draggable
attribute to true
. To disable dragging or set the default behavior, use draggable="false | auto"
.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Example to Perform Drag and Drop</title>
<link rel="stylesheet" href=" css/ style.css" />
</head>
<body>
<div class="parent">
<div class="origin">
<div id="element-1"
class="draggable-element"
draggable="true" >
TASK
</div>
</div>
<div class="example-dropzone" >
DONE
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Copy the code into your file, save it, and you can close it.
As we all know, CSS (Cascading Style Sheets) offers many styling possibilities. Let's style each class individually.
.parent {
border: 40px solid #DEB887;
color: #800000;
display: flex;
font-family: verdana;
font-weight: bold; }
.origin {
flex-basis: 100%;
flex-grow: 3;
padding: 5px; }
.draggable-element {
background-color: #FFDEAD;
font-family: verdana;
font-weight: bold;
margin-bottom: 5px;
margin-top: 5px;
padding: 5px; }
.dropzone {
background-color: #FFEBCD;
flex-basis: 100%;
flex-grow: 2;
padding: 5px;}
Since we’ve already linked the CSS file in our HTML, open the page in a browser. You'll see a prohibited sign if you try to grab the draggable element. This means dragging is not yet implemented, so let’s move to the next step.
Nothing will happen when we try to move the element without handling the drag-and-drop events. We’ll use HTML attributes to assign event handlers and trigger the drag operation with the format on{event}. Remember that the draggable element and the target zone have different events.
In our project, we will use the main event handlers:
The ondragstart
event handler triggers when the dragstart event occurs on the draggable element.
As mentioned earlier, the dragover
event refers to the drop zone. It is triggered when the dragged element moves within the target zone.
The ondrop
event handler signals the completion of the drag operation, meaning when the dragged element is dropped into the drop zone.
To store data during the drag process, we’ll use the dataTransfer
object. This object is linked to the Event object. You can use three methods of dataTransfer
:
setData()
– sets the data for the drag operation.
clearData()
– removes all data when called.
getData()
– returns all data set during the dragstart event.
Now, open the script.js
file and create a corresponding function for each of the events that will be triggered.
Since our block contains text, we will use text/plain
for dragging.
function onDragStart(event) {
event
.dataTransfer
.setData('text/plain', event.target.id);
event
.currentTarget
.style
.backgroundColor = 'red';
}
function onDragOver(event) {
event.preventDefault();
}
function onDrop(event) {
const id = event
.dataTransfer
.getData('text');
const draggableElement = document.getElementById(id);
const dropzone = event.target;
dropzone.appendChild(draggableElement);
event
.dataTransfer
.clearData(); }
We’ll apply the preventDefault()
method to cancel the default browser behavior. This way, the events will only occur when the specific conditions are met. We will add three event handlers in the first and second <div>
elements in the HTML file.
Final code:
<!DOCTYPE html>
<html lang="en">
<head>
<title> Example to Perform Drag and Drop</title>
<link rel="stylesheet" href=" css/ style.css" />
</head>
<body>
<div class="example-parent">
<div class="example-origin">
<div id="draggable-1"
class="example-draggable"
draggable="true"
ondragstart="onDragStart(event);" >
draggable
</div>
</div>
<div class="example-dropzone"
ondragover="onDragOver(event);"
ondrop="onDrop(event);">
dropzone
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Our example demonstrated how to move elements using HTML Drag and Drop with pure JavaScript. By following this step-by-step approach, you can move on to implement larger projects (which can always be hosted on cloud servers like Hostman). Remember, in development, a well-thought-out graphical interface establishes effective communication between the user and the application or website.