o7planning

Javascript DragEvent Tutorial with Examples

  1. DragEvent

1. DragEvent

DragEvent is an interface that represents events occurring during drag & drop of an object from one place to another. An user initiates a drag by putting a pointer device (such as a mouse) on the surface of an object, press down, and move the pointer device to another place, then release the pointer device, to drop the object into a new location.
DragEvent is a sub-interface of MouseEvent, therefore, it inherits all the properties and methods of MouseEvent.
Below is the list of the types of events that will occur during drag and drop
Event
Element Type
Description
dragstart
Dragged Element
The event occurs when the user starts to drag an element
drag
Dragged Element
The event occurs when an element is being dragged
dragend
Dragged Element
The event occurs when the user has finished dragging an element
dragenter
Drop Target
The event occurs when the dragged element enters the drop target
dragover
Drop Target
The event occurs when the dragged element is over the drop target
dragleave
Drop Target
The event occurs when the dragged element leaves the drop target
drop
Drop Target
The event occurs when the dragged element is dropped on the drop target
Illustrations of events occurring during drag drop.
Property
Description
dataTransfer
Returns the data that is dragged/dropped
See a simple example:
dragevents-example.html
<!DOCTYPE html>
<html>
   <head>
      <title>DragEvent Example</title>

      <script src="dragevents-example.js"></script>
      <style>
      .droptarget-div {
        float: left;
        width: 100px;
        height: 55px;
        margin: 25px 25px 5px 5px;
        padding: 10px;
        border: 1px solid black;
      }
      #dragtarget-div {
         background: #eee;
         padding: 5px;
      }
      </style>
   </head>
   <body>

      <h3>DragEvent example</h3>

      <p id="log-div">..</p>

      <!-- Drop Target 1 -->
      <div class="droptarget-div"
            ondragenter= "ondragenterHandler(event)"
            ondragover="dragoverHandler(event)"
            ondrop="dropHandler(event)">

         <p id="dragtarget-div"
               ondragstart="dragstartHandler(event)"
               ondrag="dragHandler(event)"
               draggable="true">
            Drag me!
          </p>

      </div>

      <!-- Drop Target 2 -->
      <div class="droptarget-div"
           ondragenter= "ondragenterHandler(event)"
           ondragover="dragoverHandler(event)"
           ondrop="dropHandler(event)">

      </div>




   </body>
</html>
dragevents-example.js
// --------- Handlers for 'Dragged Element' ------------------
function dragstartHandler(evt) {
  evt.dataTransfer.setData("MyDraggedElementId", evt.target.id);
}

// dragging ...
function dragHandler(evt) {
   showLog("The p element is being dragged");
}


// --------- Handlers for 'Drop Target' ------------------

function ondragenterHandler()  {
   showLog("The p element enter drop-target");
}

// When 'over' you can 'release mouse' to 'drop'.
function dragoverHandler(evt) {
    evt.preventDefault(); // Important!!
}

function dropHandler(evt) {
   evt.preventDefault(); // Important!!

   var elementId = evt.dataTransfer.getData("MyDraggedElementId");
   evt.target.appendChild(document.getElementById(elementId));
   showLog("The p element was dropped");
}

// -------------------------------------------------------

function showLog(text)  {
   document.getElementById("log-div").innerHTML = text;
}
-
For example, users drag files on their computer and drop into a <div> element, you can read the basic information, and the content of the files that the user has dropped.
When the drop event occurs, event.dataTransfer.files returns a FileList object, which contains a list of File objects.
drop-files-example.html
<!DOCTYPE html>
<html>

<head>
    <title>DragEvent Example</title>
    <meta charset="UTF-8">

    <script src="drop-files-example.js"></script>

    <style>
        #drop-area {
            border: 1px solid blue;
            padding: 15px;
        }
    </style>

</head>

<body>

    <h3>Drop files example</h3>

    <div id="drop-area" ondragover="dragoverHandler(event)" ondrop="dropHandler(event)">
        Drop files here
    </div>

    <output id="log-div"></output>

</body>

</html>
drop-files-example.js
function dropHandler(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    // FileList object.
    var files = evt.dataTransfer.files;

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
        output.push('<li><strong>', escape(f.name), //
            '</strong> (', f.type || 'n/a', ') - ', //
            f.size, ' bytes, last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
            '</li>');
    }
    document.getElementById('log-div').innerHTML = '<ul>' + output.join('') + '</ul>';
}

function dragoverHandler(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    // Explicitly show this is a copy.
    evt.dataTransfer.dropEffect = 'copy';
}

ECMAScript, Javascript Tutorials

Show More