Search code examples
htmldrag-and-drop

Dropped-in state with Html5


I have found this snippet in html5:

<script>
    function drag(target, evt) {
        evt.dataTransfer.setData("Text", target.id);
    }
    function drop(target, evt) {
        var id = evt.dataTransfer.getData("Text");
        target.appendChild(document.getElementById(id));
        evt.preventDefault();
    }
</script>

<img src="../#"  id="block1" ondragstart="drag(this, event)" alt="block1">
<img src="../#"  id="block2" ondragstart="drag(this, event)" alt="block2"><br/>

<div class="box" ondragover="return false" ondrop="drop(this, event)">
    <p>Box 1</p>
</div>
<div class="box" ondragover="return false" ondrop="drop(this, event)">
    <p>Bax 2</p>
</div>
<div style="clear:both"></div>

How can I receive which block is in box1, in box2, etc. We can't differentiate both boxes there, no?


Solution

  • First, give the boxes unique id attributes. Then, you can use the target parameter to the drop() function:

    <div class="box" ondragover="return false" ondrop="drop(this, event)" id="box1">
        <p>Box 1</p>
    </div>
    <div class="box" ondragover="return false" ondrop="drop(this, event)" id="box2">
        <p>Box 2</p>
    </div>
    

    Then you can use the value target.id to distinguish between the two divs.

    Also, you can use the target parameter of the drag() function to get the id attribute of the block being dragged, assuming the blocks have id attributes assigned to them.

    Here's a working jsFiddle.

    Lots of information on drag-and-drop for HTML5 here:

    http://www.w3.org/TR/html5/dnd.html#dnd