Home > Articles > Web Development > HTML/CSS

  • Print
  • + Share This
This chapter is from the book

Handling Drop Events

When the user drops a draggable <div> element on an allowed target <div> element, how do we move the draggable <div> to the target? That turns out to be simple—we'll just use the built-in JavaScript function appendChild to append the draggable <div> element to the current target <div> element.

When the user drops a draggable <div> element on a target, the ondrop event occurs in the target element, and we have connected a JavaScript function named drop() to implement the drop operation. To add drop() to the draganddrop.html example, follow these steps:

  1. Open draganddrop.html using a text editor such as Windows WordPad.
  2. Add the following code to the <script> section of dragdrop.html, creating the drop() function and getting the ID of the dragged item (iddraggable):
    function drop(e)
    {
      var iddraggable =
        e.dataTransfer.getData("Data");
      .
      .
      .
    }
  3. Add the following code to the drop() function to append the draggable <div> element to the target <div> element, as well as stopping further propagation of the event in the browser with the stopPropagation() function (returning a value of false also stops further propagation of the event):
    function drop(e)
    {
      var iddraggable =
        e.dataTransfer.getData("Data");
      e.target.appendChild
        (document.getElementById(iddraggable));
      e.stopPropagation();
      return false;
    }
  4. Save draganddrop.html. Make sure you save this code in text format (the default format for WordPad, for example, is RTF, rich-text format, which won't work with browsers).

Now you've handled the drop operation.

  • + Share This
  • 🔖 Save To Your Account