I'm trying to combine jQuery draggable, droppable, and sortable; however, I keep having problems. Can anybody help me?
Basically, the idea is illustrated here:
- A, B, C, D, E tiles can be moved between the upper droppable and the sortable.
- The custom (*) tile can be moved only between the left-side droppable and the sortable.
Also, I'm trying to be able to deactivate and reactivate all these at any standing when necessary.
This is what I have, but it's very buggy and not pretty:
JS
var gameContainer = $(".game");
var myTray = $(".tray").sortable({
containment: gameContainer,
helper: "clone",
revert: 100,
tolerance: "pointer",
update: function(ev, ui) {
ui.item.addClass("ontray").css({
"left": "0px",
"position": "static",
"top": "0px"
});
}
}).disableSelection();
var setTileDraggable = function(tileSelector) {
tileSelector.draggable({
connectToSortable: myTray,
containment: gameContainer,
helper: "original",
revert: "invalid"
}).disableSelection();
};
var myBoard = $(".board").droppable({
accept: ".tile:not(.red)",
drop: function(ev, ui) {
if (ui.draggable.hasClass("ontray")) {
// tile (not red) coming from tray, place it into .tiles child div
var cloneTile = ui.draggable.clone().removeClass("ontray").show();
myBoard.children(".tiles").append(cloneTile);
var dropx = ui.offset.left - myBoard.offset().left;
var dropy = ui.offset.top - myBoard.offset().top;
cloneTile.css({
"left": dropx + "px",
"position": "absolute",
"top": dropy + "px"
});
setTileDraggable(cloneTile);
ui.helper.remove();
ui.draggable.remove();
}
}
}).disableSelection();
var myCustomTile = $(".custom").droppable({
accept: ".tile.red",
drop: function(ev, ui) {
if (ui.draggable.hasClass("ontray")) {
// red tile coming from tray
var cloneTile = ui.draggable.clone().removeClass("ontray").show();
myCustomTile.append(cloneTile);
setTileDraggable(cloneTile);
setTileClick(cloneTile);
ui.helper.remove();
ui.draggable.remove();
} else {
// red tile staying, move back to original position
ui.draggable.stop(true, false).animate({
"left": "0px",
"top": "0px"
});
}
}
}).disableSelection();
// set up draggables
setTileDraggable(myBoard.children(".tiles").find(".tile"));
setTileDraggable(myCustomTile.find(".tile"));
HTML
<div class="game">
<div class="board">
<div class="tiles">
<div class="tile">D</div>
<div class="tile">B</div>
<div class="tile">E</div>
</div>
</div>
<div class="custom">
<div class="tile red">X</div>
</div>
<div class="tray">
<div class="tile">C</div>
<div class="tile">A</div>
</div>
</div>