0

I am trying to drag and drop some items. I can drag a div over to the drop zone div, and it works fine. However, when i drag another div, i can actually drop it inside the previously dropped div. I do not want this. I want the drop zone to be the only place that can accept a dropped div.

    <div class='container-fluid'>
        <div class='row'>
            <div class='col-sm-12' style='padding:0px;'>
                <div class='col-sm-6'>
                    <div class='row'>
                        <div class='col-sm-2 drag-example' id='drag-1' 
                            draggable='true' ondragstart='drag(event)'></div>
                        <div class='col-sm-2 drag-example' id='drag-2' 
                            draggable='true' ondragstart='drag(event)'></div>
                        <div class='col-sm-2 drag-example' id='drag-3' 
                            draggable='true' ondragstart='drag(event)'></div>
                    </div>
                </div>
                <div class='col-sm-6'>
                    <div class='row'>
                        <div class='col-sm-10 drop-example' 
                            ondrop='drop(event)' ondragover='allowDrop(event)' 
                                id='drop-div'></div>
                        </div>
                   </div>
                </div>
        </div>
    </div>


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).cloneNode(true));
}
  • Possible duplicate of [prevent drop inside a child element when drag & dropping with JS](https://stackoverflow.com/questions/28203585/prevent-drop-inside-a-child-element-when-drag-dropping-with-js) – Kapil Kumar Sep 04 '18 at 17:22

1 Answers1

0
  1. Change the drop function and add second parameter.
  2. append the element to the second parameter passed to drop function.
  3. pass this reference in drop function as second parameter

function allowDrop(ev) {
  ev.preventDefault();
}

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

// change 1 :: added el
function drop(ev, el) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  // change 2 :: append to el
  el.appendChild(document.getElementById(data).cloneNode(true));
}
.drag-example {
  border: 1px Solid Black;
  width: 50px;
  height: 50px;
  margin-bottom: 5px;
}

.drop-example {
  border: 1px Solid Red;
  width: 50px;
  height: 50px;
}
<div class='drag-example' id='drag-1' draggable='true' ondragstart='drag(event)'></div>
<!-- change 3 :: pass this to drop -->
<div class='drop-example' ondrop='drop(event, this)' ondragover='allowDrop(event)' id='drop-div'></div>