Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Execute a script at the start of a drag operation in HTML?
The ondragstart attribute in HTML executes a JavaScript function when a user begins dragging an element. This event is the first to fire in the HTML5 drag and drop sequence, allowing you to set up data transfer and configure the drag operation before the element starts moving.
Syntax
Following is the syntax for the ondragstart attribute −
<element ondragstart="function(event)">Content</element>
The ondragstart attribute accepts a JavaScript function that receives a DragEvent object containing information about the drag operation.
How It Works
When a drag operation begins, the ondragstart event fires immediately. This is typically where you use the dataTransfer object to store data that will be available during the drop operation. The dataTransfer.setData() method allows you to specify what data gets transferred when the element is dropped.
The drag and drop sequence follows this order −
ondragstart − Fires when dragging begins
ondrag − Fires continuously while dragging
ondragover − Fires when dragged element is over a drop target
ondrop − Fires when the element is dropped
Basic Example
Following example demonstrates a simple drag operation with ondragstart −
<!DOCTYPE html>
<html>
<head>
<title>Simple Drag Start Example</title>
<style>
.dragbox {
width: 120px;
height: 40px;
background-color: #4CAF50;
color: white;
text-align: center;
line-height: 40px;
margin: 10px;
cursor: move;
}
.status {
margin: 10px;
padding: 10px;
background-color: #f0f0f0;
border: 1px solid #ccc;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<div class="dragbox" draggable="true" ondragstart="startDrag(event)">
Drag Me!
</div>
<div id="status" class="status">Ready to drag...</div>
<script>
function startDrag(event) {
document.getElementById("status").innerHTML = "Drag operation started!";
event.dataTransfer.setData("text/plain", "Dragged element data");
}
</script>
</body>
</html>
When you start dragging the green box, the status message changes to indicate the drag operation has begun −
Green box with "Drag Me!" text Status: "Drag operation started!" (appears when drag begins)
Complete Drag and Drop Example
Following example shows a complete drag and drop implementation using ondragstart along with other drag events −
<!DOCTYPE html>
<html>
<head>
<title>Complete Drag and Drop</title>
<style>
.drag-container {
float: left;
width: 150px;
height: 80px;
border: 2px dashed #876587;
margin: 15px;
padding: 10px;
background-color: #f9f9f9;
}
.draggable-item {
background-color: #4285f4;
color: white;
padding: 10px;
text-align: center;
cursor: move;
border-radius: 4px;
}
.status-box {
clear: both;
margin: 20px 0;
padding: 10px;
background-color: #e8f0fe;
border: 1px solid #4285f4;
border-radius: 4px;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<div class="drag-container" ondrop="drop(event)" ondragover="allowDrop(event)">
<div class="draggable-item" ondragstart="dragStart(event)" ondrag="dragging(event)"
draggable="true" id="item1">
Drag Me!
</div>
</div>
<div class="drag-container" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="statusBox" class="status-box">
Ready to drag. Drag the blue box to the right container.
</div>
<script>
function dragStart(event) {
event.dataTransfer.setData("text", event.target.id);
document.getElementById("statusBox").innerHTML = "Drag started! Element ID: " + event.target.id;
}
function dragging(event) {
document.getElementById("statusBox").innerHTML = "Currently dragging...";
}
function allowDrop(event) {
event.preventDefault();
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
document.getElementById("statusBox").innerHTML = "Drop completed successfully!";
}
</script>
</body>
</html>
This example shows how ondragstart initiates the drag process by storing the element's ID in the data transfer object, which is then retrieved during the drop operation.
Two containers side by side - left contains blue "Drag Me!" box, right is empty Status box shows progression: "Ready to drag" ? "Drag started!" ? "Currently dragging..." ? "Drop completed!"
Setting Custom Drag Data
The ondragstart event is where you define what data accompanies the drag operation. You can store multiple data types for different drop targets.
Example
<!DOCTYPE html>
<html>
<head>
<title>Custom Drag Data</title>
<style>
.product {
display: inline-block;
width: 100px;
height: 100px;
margin: 10px;
padding: 10px;
background-color: #ff9800;
color: white;
text-align: center;
cursor: move;
border-radius: 8px;
}
.cart {
width: 300px;
height: 150px;
border: 2px solid #4CAF50;
margin: 20px;
padding: 10px;
background-color: #f0f8f0;
}
.info {
margin: 10px;
padding: 10px;
background-color: #fff3cd;
border: 1px solid #ffc107;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<div class="product" draggable="true" ondragstart="setProductData(event)"
data-name="Laptop" data-price="$999">
Laptop<br>$999
</div>
<div class="product" draggable="true" ondragstart="setProductData(event)"
data-name="Phone" data-price="$499">
Phone<br>$499
</div>
<div class="cart" ondrop="addToCart(event)" ondragover="allowDrop(event)">
<h3>Shopping Cart</h3>
<div id="cartItems">Drop products here...</div>
</div>
<div id="dragInfo" class="info">Drag products to cart</div>
<script>
function setProductData(event) {
var name = event.target.getAttribute('data-name');
var price = event.target.getAttribute('data-price');
event.dataTransfer.setData('text/plain', name);
event.dataTransfer.setData('application/json', JSON.stringify({
name: name,
price: price
}));
document.getElementById('dragInfo').innerHTML = 'Dragging: ' + name + ' (' + price + ')';
}
function allowDrop(event) {
event.preventDefault();
}
function addToCart(event) {
event.preventDefault();
var productData = JSON.parse(event.dataTransfer.getData('application/json'));
document.getElementById('cartItems').innerHTML +=
'<div>Added: ' + productData.name + ' - ' + productData.price + '</div>';
document.getElementById('dragInfo').innerHTML = 'Product added to cart!';
}
</script>
</body>
</html>
This example shows how ondragstart can store complex data using JSON format, allowing rich information transfer during drag operations.
Two orange product boxes (Laptop $999, Phone $499) Green shopping cart area below Info box shows drag status and cart additions
Key Points
The
ondragstartevent fires only when dragging begins, not during the drag motion.Use
event.dataTransfer.setData()to store information that drop targets can access.The draggable element must have
draggable="true"attribute for the event to work.You can store multiple data formats using different MIME types in the same drag operation.
The
ondragstartevent is essential for implementing functional drag and drop interfaces.
Conclusion
The ondragstart attribute is crucial for HTML drag and drop functionality, as it defines what data gets transferred when dragging begins. By using event.dataTransfer.setData() within the ondragstart handler, you can create rich, interactive drag and drop experiences that pass meaningful information between draggable elements and drop targets.
