Javascript DOM ondragover Event via HTML Tag ondragover function

Introduction

In JavaScript:

object.ondragover = function(){
       myScript};

This example uses the HTML DOM to assign an "ondragstart" and "ondrag" event to a p element and an "ondragover" and "ondrop" event to a div element.

View in separate window

<!DOCTYPE HTML>
<html>
<head>
<style>
#droptarget {//from w  ww  .ja  v  a  2  s .c o  m
  float: left;
  width: 200px;
  height: 35px;
  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.ondragstart = function(event) {
  event.dataTransfer.setData("Text", event.target.id);
};

drag.ondrag = function(event) {
  document.getElementById("demo").innerHTML = "The p element is being dragged.";
};

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

drop.ondrop = 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