HTML and CSS Reference
In-Depth Information
eXerCISe 14-6. aDDING prOMOtION
1.
Add the kingMe() function shown in Listing 14-7 to the existing script element.
Listing 14-7. Implementing the kingMe() function
function kingMe(piece) {
// If we're already a king, just return
if (piece.id.substr(0, 1) === "W" || piece.id.substr(0, 1) === "B")
return;
var newPiece;
// If this is a white piece on the 7th row
if (piece.id.substr(0, 1) === "w" && piece.id.substr(2, 1) === "7") {
newPiece = document.createElement("img");
newPiece.src = "Images/WhiteKing.png";
newPiece.id = "W" + piece.id.substr(1, 2);
}
// If this is a black piece on the 0th row
if (piece.id.substr(0, 1) === "b" && piece.id.substr(2, 1) === "0") {
var newPiece = document.createElement("img");
newPiece.src = "Images/BlackKing.png";
newPiece.id = "B" + piece.id.substr(1, 2);
}
// If a new piece was created, set its properties and events
if (newPiece) {
newPiece.draggable = true;
newPiece.classList.add("piece");
newPiece.addEventListener('dragstart', dragStart, false);
newPiece.addEventListener('dragend', dragEnd, false);
var parent = piece.parentNode;
parent.removeChild(piece);
parent.appendChild(newPiece);
}
}
2.
The kingMe() function simply returns if the id prefix is ether “B” or “W”, which
indicates this is already a king. It then checks to see if this is a white piece on row 7
or a black piece on row 0. If so, a new img element is created with the appropriate
src and id properties. If a new img was created the function then sets all of the
properties and events, removes the existing img element from the div element and
adds the new one.
3.
Modify the drop() function to call the kingMe() function after a drop has been
performed by adding the line shown in bold.
Search WWH ::




Custom Search