See this fiddle showing the main problem and some others fixed.
OK, the immediate problem - receiving an error when you dropped on a piece's starting position is that you were looking up the element by the td id name prefixed with S
which happens to be the same as the span that you are dragging around:
if (tdid.length < 3) {
spanid = 'S' + tdid; //id of span by concatenating "S" to tdid
}
For example,
<td id="A0"...
contains span
<span id="SA0"
Note that S
+ A0
will always equal SA0
which is the ID of the span (piece) that you are dragging around.
There were a few other issues that I fixed:
- All table cells, even ones that didn't have a piece had a draggable span. This caused some conflicts and errors when dragging around as it was removed after a drag which caused problems with the logic in the code when a piece was dragged back to where it had visited.
- The item can be dropped on a
td
or another piecespan
, you need to handle both. - You lose the pointer icon after moving because it is no longer a link (
a
). So, I added thecursor:pointer
css.
The main changes to the logic were in function drop(ev) {
, specifically the code to handle drops to different locations and to get the inner span:
tdid = ev.target.id; //td id of the target
//if (tdid.length < 3) {
// spanid = 'S' + tdid; //id of span by concatenating "S" to tdid
//}
//else {
// spanid = tdid;
//}
var ttd = document.getElementById(tdid);
var tgtPieceElem;
if( ttd.nodeName.toLowerCase()=='span')//dropped onto another piece
{
tgtPieceElem = ttd;
}
else //dropped onto table-cell
{
var tgtPieces = ttd.getElementsByTagName('span');
tgtPieceElem = (tgtPieces.length==1)?tgtPieces[0]:null;
}
if (tgtPieceElem) {
tgtPiece = tgtPieceElem.innerHTML; //gives code of target
and the final else to handle drop to an empty cell.
else
{
ev.target.innerHTML = "";
ev.target.appendChild(document.getElementById(src)); //append src piece into target piece
alert(src);
}
Besides this, I have the following recommendations: -
- The links have duplicate ids for example, all pawn links have the id
pawn
. Ids should be unique on the page, use a class instead. - I am not sure if the links
a
was done because you wanted links or just to show that the elements could be clicked. If the latter, then I suggest removing the links and using the csscursor:pointer instead
and css for colour styling. If you want the links, then currently the pieces are dragged without the links, so they lose them when dropped. You will need to insert the links into the new cell as well. - You probably want some class on the pieces so that you can recognize in drop that a valid piece is being dropped and exit the function if not. Currently you can drop an image or any other draggable element which causes an error in the code.
- As others have mentioned, it is best to keep game logic separate from presentation. However, most of the errors were related to presentation, so you will need to do both (fix presentation errors and separate logic).