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
Which event occurs in JavaScript when a dragged element is dropped?
The ondrop event occurs when a dragged element is successfully dropped on a valid drop target. This event is part of the HTML5 Drag and Drop API and must work together with ondragover to enable dropping functionality.
How Drag and Drop Works
The drag and drop process involves several events:
-
ondragstart- When dragging begins -
ondragover- When dragged element is over a drop target -
ondrop- When element is dropped on target -
ondragend- When dragging operation ends
Key Requirements
For ondrop to work properly:
- The drop target must handle
ondragoverand callpreventDefault() - The
ondrophandler must also callpreventDefault() - The draggable element needs
draggable="true"attribute
Example
<!DOCTYPE html>
<html>
<head>
<style>
.drag {
float: left;
width: 100px;
height: 35px;
border: 2px dashed #876587;
margin: 15px;
padding: 10px;
}
</style>
</head>
<body>
<div class="drag" ondrop="drop(event)" ondragover="dropNow(event)">
<p ondragstart="dragStart(event)" ondragend="dragEnd(event)" draggable="true" id="dragtarget">Drag!</p>
</div>
<div class="drag" ondrop="drop(event)" ondragover="dropNow(event)"></div>
<div id="box"></div>
<p>Drag the left box to the right or drag the right box to the left.</p>
<script>
function dragStart(event) {
event.dataTransfer.setData("Text", event.target.id);
}
function dropNow(event) {
event.preventDefault();
}
function dragEnd(event) {
document.getElementById("box").innerHTML = "Dragging ends!";
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("Text");
event.target.appendChild(document.getElementById(data));
document.getElementById("box").innerHTML = "The element dropped successfully!";
}
</script>
</body>
</html>
Function Breakdown
dragStart(): Stores the dragged element's ID in the data transfer object.
dropNow(): Prevents default behavior to allow dropping on the target.
drop(): Handles the actual drop by retrieving the stored data and moving the element to the new location.
dragEnd(): Executes when the drag operation completes, regardless of success.
Common Use Cases
- File upload interfaces
- Sortable lists and tables
- Visual editors and design tools
- Task management boards
Conclusion
The ondrop event is essential for implementing drag and drop functionality in web applications. Remember to always call preventDefault() in both ondragover and ondrop handlers for proper functionality.
