JavaScript ondrop Event
You are Here:
JavaScript ondrop Event
The ondrop
event occurs when a draggable element is dropped on a valid drop target.
ondrop Event as Attribute
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p id="point">Drag the ball inside the Box:</p>
<div id="myDiv" ondrop="onDrop(event)" ondragover="onDragOver(event)"></div>
<img id="myImg" src="/football.svg" draggable="true" ondragstart="onDragStart(event)">
<script>
var x = document.getElementById("point");
function onDragOver(e){
e.preventDefault();
}
function onDragStart(e){
e.dataTransfer.setData("text", e.target.id);
}
function onDrop(e){
var data = e.dataTransfer.getData("text");
e.target.appendChild(document.getElementById(data));
x.innerHTML = "Good Job";
}
</script>
</body>
</html>
Syntax
As Attribute
<element ondrop="JavaScript">
As Property
object.ondrop = function(){
// code
};
Using Event Listener
object.addEventListener("drop" , myScript);
ondrop Event as Property
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p id="point">Drag the ball inside the Box:</p>
<div id="myDiv" ondragover="onDragOver(event)"></div>
<img id="myImg" src="/football.svg" draggable="true" ondragstart="onDragStart(event)" width="95" height="95">
<script>
var x = document.getElementById("point");
var myDiv = document.getElementById("myDiv");
function onDragOver(e){
e.preventDefault();
}
function onDragStart(e){
e.dataTransfer.setData("text", e.target.id);
}
myDiv.ondrop = function(e){
var data = e.dataTransfer.getData("text");
e.target.appendChild(document.getElementById(data));
x.innerHTML = "Good Job";
}
</script>
</body>
</html>
Using addEventListener() Method
Note: The addEventListener() method is not supported in Internet Explorer 8 and below.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p id="point">Drag the ball inside the Box:</p>
<div id="myDiv" ondragover="onDragOver(event)"></div>
<img id="myImg" src="/football.svg" draggable="true" ondragstart="onDragStart(event)" width="95" height="95">
<script>
var x = document.getElementById("point");
var myDiv = document.getElementById("myDiv");
function onDragOver(e){
e.preventDefault();
}
function onDragStart(e){
e.dataTransfer.setData("text", e.target.id);
}
myDiv.addEventListener("drop", function(e){
var data = e.dataTransfer.getData("text");
e.target.appendChild(document.getElementById(data));
x.innerHTML = "Good Job";
});
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.