Home > Articles > Web Development > HTML/CSS

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

Allowing Dragged Objects to Be Dropped on Certain Targets

When the user drags a draggable <div> element over a target, that target's ondragover event occurs, and we've tied that event to a function named over(). You can use the over() function to indicate whether the dragged item may be dropped on the current target. If you return a value of true from this function, the dragged item may not be dropped; returning a value of false means that it can be dropped.

To create the over() function, 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 over() function and getting the ID of the dragged item (iddraggable) and the ID of the target (id):
    function over(e)
    {
      var iddraggable =
        e.dataTransfer.getData("Data");
      var id = e.target.getAttribute('id');
      .
      .
      .
    }
  3. Add the following code to the over() function to indicate that any dragged item may be dropped on target 1, that draggable <div> element 3 may be dropped on target 2 only, and that draggable <div> elements 1 and 2 may be dropped on target 3 only:
    function over(e)
    {
      var iddraggable =
        e.dataTransfer.getData("Data");
      var id = e.target.getAttribute('id');
    
      if(id =='target1')
             return false;
    
      
             if((id =='target2')
             && iddraggable == 'draggable3')
             return false;
    
      
             else if(id =='target3'
             && (iddraggable == 'draggable1' ||
             iddraggable =='draggable2'))
             return false;
    
      
             else
             return true;
    }
  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 indicated to the browser which draggable <div> elements may be dropped on which target <div> elements.

  • + Share This
  • 🔖 Save To Your Account