Home > Articles > Web Development > HTML/CSS

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

Starting the Drag Operation

When the user starts dragging a draggable <div> element in our example, that <div> element's ondragstart event occurs, and we've tied that event to a JavaScript function named start().

In this task, we'll write the start() function to get the dragging operation started. That involves three steps: setting the allowed drag operation to "move" so the draggable <div> element that the user wants to drag may be dragged, storing the ID of the element that's being dragged so we can move it when it's dropped, and setting the image that the user will drag around.

To do all these things, follow these steps:

  1. Open draganddrop.html using a text editor such as Windows WordPad.
  2. Add the following code to the <head> section of dragdrop.html, starting a new <script> element, and creating the start() function:
    <script type="text/javascript">
      function start(e)
      {
        .
        .
        .
      }
  3. Add the following code to the start() function to indicate that the draggable <div> element the user is attempting to drag may indeed be moved (which you do by setting the dataTransfer.effectAllowed property of the event object passed to the start() function to "move"):
    <script type="text/javascript">
      function start(e)
      {
        e.dataTransfer.effectAllowed='move';
        .
        .
        .
      }
  4. Add the following code to the start() function to store the ID of the <div> element being dragged so we can move it when it's dropped:
    <script type="text/javascript">
      function start(e)
      {
        e.dataTransfer.effectAllowed='move';
        e.dataTransfer.setData("Data",
           e.target.getAttribute('id'));
        .
        .
        .
      }
  5. Add the following code to the start() function to set the drag image to the draggable <div> element, with an offset of (0, 0):
    <script type="text/javascript">
      function start(e)
      {
        e.dataTransfer.effectAllowed='move';
        e.dataTransfer.setData("Data",
          e.target.getAttribute('id'));
        e.dataTransfer.setDragImage(e.target, 0, 0);
        return true;
      }
  6. 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 the user will be able to drag the draggable <div> elements in this example.

  • + Share This
  • 🔖 Save To Your Account