Vincent Vincent - 5 months ago 19
jQuery Question

Disable drop in childs of div (Html5 drag and drop )

HTML

<div id="participants" ondrop="drop(event)" ondragover="allowDrop(event)" style="width:400px; min-height:300px; display:inline; float:left; border: 1px solid black;">
<h3 style="margin:10px;">Participants</h3>
</div>



<div id="users" ondrop="drop(event)" ondragover="allowDrop(event)" style="width:400px; min-height:300px; float:right; border: 1px solid black;" >

<p class="draggable" draggable="true" ondragstart="drag(event)" ondrop="return false;" >draggable content</p>
</div>


Javascript

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

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

drop = function(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
if (data) {
var childElement = document.getElementById(data);
if (childElement) {
ev.target.appendChild(childElement);
}
}
}


The following code works fine, but I only want things to be moved from one div to another. Right now you can also drop a p inside another p (even though I tried to prevent this with ondrop="return false;").

How can I disable p tags to be dropped inside other p tags?
Note: the draggable elements are inserted by jQuery.html method

Answer

My temp solution is to check the class before dropping (added class droppable to the 2 divs: users and participants)

drop = function(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("Text");
            if (data) {
                var childElement = document.getElementById(data);
                if (childElement) {
                    if($(ev.target).hasClass( "droppable" ))    {           //Only allow drop inside the 2 divs
                        ev.target.appendChild(childElement);
                    }
                    if($(ev.target).hasClass( "draggable" ))    {           //put in parent when dropped on draggable
                        console.log('$(ev.target).parent()', $(ev.target).parent());
                        $(ev.target).parent()[0].appendChild(childElement);
                    }
                    return false;
                }
            }
        }
Comments