Search code examples
javascripthtmldrag-and-drop

Drag and drop, the drag element id and where to drop id


I'm working with the drag and drop using HTML5 and JavaScript, I want to get the id of the dragged element and the id where to dragged.

The first part was easy, but getting the id where to drag that's my problem.

This is my code HTML :

<div class="form-group" ondrop="drop(event)" ondragover="allowDrop(event, this)" id="drop1" ondrop="getID(this, ev)" >
<label class="col-sm-12 control-label">Equipe 1</label>
</div>

<div class="form-group"  draggable="true" ondragstart="drag(event)" id="drag5" ondrop="drop(event)" ondragover="allowDrop(event)">
<table>
   <tr>
       <td><img alt="image" class="img-circle" src="img/profile_small.jpg" /></td>
       <td><label class="control-label">Employé 4</label></td>
   </tr>
</table>
</div>

and here the Javascript :

<script>
            function allowDrop(ev) {
                ev.preventDefault();
            }

            function drag(ev) {
                ev.dataTransfer.setData("text", ev.target.id);
            }

            function drop(ev) {
                ev.preventDefault();
                var data = ev.dataTransfer.getData("text");
                ev.target.appendChild(document.getElementById(data));
                alert(document.getElementById(data).textContent+" Dropped");
            }
</script>

Thank you


Solution

  • <style>
    #drag5
    {
      border: 1px solid #ccc;
      color:blue;
      width:300px;
    }
    #drop1
    {
      border: 1px solid #ccc;
      color:blue;
      width:500px;
      height:200px;
    }
    </style>
    
    <script>
    function allowDrop(ev) {
        ev.preventDefault();
    }
    
    function drag(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
    }
    
    function drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
    </script>
    
    <div class="form-group"  draggable="true" ondragstart="drag(event)" id="drag5" >
    
    <table>
       <tr>
           <td><img alt="image" class="img-circle" src="https://lh3.googleusercontent.com/-ekut6zqo6VY/AAAAAAAAAAI/AAAAAAAAACk/6qR5GAaQ00I/photo.jpg?sz=32" /></td>
           <td><label class="control-label">Employé 4</label></td>
       </tr>
    </table>
    </div>
    <br/><br/><br/>
    
    <div id="drop1" class="form-group" ondrop="drop(event)" ondragover="allowDrop(event)">
    
    <label class="col-sm-12 control-label">Equipe 1</label>
    </div>