Reputation: 1226
I have simple table with two cells. I change w3 school code(for drag and drop) to one image, when drag over second, take second image place and second image disappears. But problem come when there is no image in cell, then cell is gone. How to check is there image in cell?
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");
var el = ev.target.parentNode;
ev.target.appendChild(document.getElementById(data));
el.appendChild(document.getElementById(data).cloneNode(true));
var x = el.classList.contains('dropzone');
if (!x) {
ev.target.remove();
}
}
th, td{
border: solid black;
width: 100px;
height: 100px;
padding: 0px;
}
table{
width: 300px;
}
img{
width: 100px;
}
<table>
<tr>
<td ondrop="drop(event)" ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="a8" src="http://images5.fanpop.com/image/photos/27700000/desert-windows-7-vista-and-xp-picks-27752343-500-375.jpg"></td>
<td ondrop="drop(event)" ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="b8" src="http://images5.fanpop.com/image/photos/27700000/jellyfish-windows-7-vista-and-xp-picks-27753183-500-375.jpg"></td>
</tr>
</table>
Upvotes: 1
Views: 108
Reputation: 4015
you can loop throught td elements and add ondrop event in you javascript code, So you can know which element has fired the event.
Then check if this element has a child inside.
If not => don't perform action (no image elements inside), else => perform action (there is an image elements inside).
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
var td=document.getElementsByTagName("td");
for(var i=0; i < td.length;i++){ //bind ondrop event to all td, so it will be easier to get the element which fired the event
td[i].ondrop=function(ev){
ev.preventDefault();
if (this.hasChildNodes()) { //check if got children nodes (if got img inside)
var data = ev.dataTransfer.getData("text");
var el = ev.target.parentNode;
ev.target.appendChild(document.getElementById(data));
el.appendChild(document.getElementById(data).cloneNode(true));
var x = el.classList.contains('dropzone');
if (!x) {
ev.target.remove();
}
}
}
}
th, td{
border: solid black;
width: 100px;
height: 100px;
padding: 0px;
}
table{
width: 300px;
}
img{
width: 100px;
}
<table>
<tr>
<td ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="a8" src="http://images5.fanpop.com/image/photos/27700000/desert-windows-7-vista-and-xp-picks-27752343-500-375.jpg"></td>
<td ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="b8" src="http://images5.fanpop.com/image/photos/27700000/jellyfish-windows-7-vista-and-xp-picks-27753183-500-375.jpg"></td>
</tr>
</table>
For more details how to check if element has any children, check answers here
Upvotes: 1