Reputation: 29
i'm using jquery and trying to drag and drop two elements divs simultaneously at the same time as one single div inside a table with nine cells (grids) here's the code,
HTML
<table border="1" class="mainTable">
<tr>
<td id="11">
<div class="dragDiv" id="1"></div>
</td>
<td id="12"><div class="dragDiv" id="2"></div></td>
<td id="13"> </td>
</tr>
<tr>
<td id="21"> </td>
<td id="22">
</td>
<td id="23"> </td>
</tr>
<tr>
<td id="31"> </td>
<td id="32"> </td>
<td id="33">
</td>
</tr>
</table>
CSS
.mainTable {
margin: 20px auto;
padding: 0px;
}
.mainTable tr td {
width: 100px;
height: 100px;
}
.dragDiv {
text-align: center;
background-color: #00ABA9;
height: 50px;
vertical-align: middle;
margin: auto;
position: relative;
width: 100%;
}
jquery
$(function() {
$(".dragDiv").draggable({
revert: 'invalid'
});
$(".mainTable tr td").droppable({
accept: function() {
return $(this).find("*").length == 0;
},
drop: function(event, ui) {
var $this = $(this);
$this.append(ui.draggable.css({
/* manually append the element
and reset positioning */
top: 0,
left: 0
}));
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, 100, "easeOutBack");
}
});
}
});
});
i tried many answers i found on this site like this answer here and here and so many more this is my project code in Codepen I'll be glad to hear some suggestions thank you.
Upvotes: 0
Views: 95
Reputation: 799
To allow your boxes to hold multiple elements, you will need to change the accept clause to allow for any element with the class of .dragDiv
.
As you can see in the snippet attached, you can now have two elements in the same box.
(I've also added some flexbox styling and removed some unneeded styling to clean up your CSS while keeping the elements centered within their containers).
$(function() {
$(".dragDiv").draggable({
revert: 'invalid'
});
$(".mainTable tr td").droppable({
accept: ".dragDiv",
drop: function(event, ui) {
var $this = $(this);
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, 100, "easeOutBack");
}
});
}
});
});
.mainTable {
margin: 20px auto;
padding: 0px;
}
.mainTable tr {
display: flex;
flex-flow: row;
}
.mainTable tr td {
width: 100px;
height: 100px;
display: flex;
flex-flow: column;
justify-content: center;
}
.dragDiv {
background-color: #00ABA9;
height: 50px;
width: 100%;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
</head>
<body>
<table border="1" class="mainTable">
<tr>
<td id="11">
<div class="dragDiv" id="1"></div>
</td>
<td id="12">
<div class="dragDiv" id="2"></div>
</td>
<td id="13"></td>
</tr>
<tr>
<td id="21"></td>
<td id="22"></td>
<td id="23"></td>
</tr>
<tr>
<td id="31"></td>
<td id="32"></td>
<td id="33"></td>
</tr>
</table>
</body>
</html>
Upvotes: 0