When the pieces are horizontal, use the existing drop function, but when it is vertical add a drop that adds pieces into the grid in vertical positioning. So for adding I gave row class. which is the parent of the dropping grid piece. You can see in the HTML. so when it is vertical, we will add the next piece in the same element index but in the next row. Use if-else for toggling and drop
// If in vertical position, add the piece to the grid vertically
if (target.classList.contains('row')) {
const row = target;
const squares = row.querySelectorAll('.square');
let emptySquare = null;
squares.forEach(square => {
if (square.childElementCount === 0 && emptySquare === null) {
emptySquare = square;
}
});
// If an empty square is found, drop the piece
if (emptySquare !== null) {
const originalChild = draggableElement.children[0].cloneNode(true);
emptySquare.appendChild(originalChild);
draggableElement.removeChild(originalChild);
// Remove redPiece element if all children are dropped
if (draggableElement.childElementCount === 0) {
const redPiecesDiv = document.getElementById('redPieces');
redPiecesDiv.removeChild(draggableElement);
}
}
}
I tried this in else for vertical but it does not work.