Reputation: 6188
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
Upvotes: 2
Views: 5149
Reputation: 2030
i encountered the same unwanted behavior. i worked around it in this way:
if (ev.target.nodeName == 'LI') {
$(ev.target).after(draggedNode);
} else {
$(ev.target.closest('li')).after(draggedNode);
}
this code assumes a DOM structure something like this, where desired drop target is the list item, and unwanted drop target is the span:
...
<li>
<span></span>
</li>
<li>
<span></span>
</li>
...
Upvotes: 1
Reputation: 6188
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;
}
}
}
Upvotes: 2