Javascript DOM ondragover Event via addEventListener() method

Introduction

In JavaScript, using the addEventListener() method:

object.addEventListener("dragover",
       myScript);

This example uses the addEventListener() method to attach a "dragstart" and "drag" event to a p element, and a "dragover" and "drop" event to a div element.

View in separate window

<!DOCTYPE HTML>
<html>
<head>
<style>
#droptarget {/*from  w w w. j  ava 2  s .  c o m*/
  float: left;
  width: 200px;
  height: 45px;
  margin: 55px;
  margin-top: 105px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
</style>
</head>
<body>
<p draggable="true" id="dragtarget">Drag me into the rectangle!</p>
<div id="droptarget"></div>
<p id="demo"></p>

<script>
var drag = document.getElementById("dragtarget");
var drop = document.getElementById("droptarget");
drag.addEventListener("dragstart", function(event) {
  event.dataTransfer.setData("Text", event.target.id);
});

drag.addEventListener("drag", function(event) {
  document.getElementById("demo").innerHTML = "The p element is being dragged.";
});
drop.addEventListener("dragover", function(event) {
  event.preventDefault();
  document.getElementById("demo").innerHTML = "The p element is OVER the droptarget.";
  event.target.style.border = "4px dotted purple";
});

drop.addEventListener("drop", function(event) {
  event.preventDefault();
  var data = event.dataTransfer.getData("Text");
  event.target.appendChild(document.getElementById(data));
  document.getElementById("demo").innerHTML = "The p element was dropped.";
});
</script>

</body>
</html>
Bubbles: Yes
Cancelable: Yes
Event type: DragEvent
Supported HTML tags: All HTML elements



PreviousNext

Related