<h4>Move the Queen in Chessboard Game</h4>
<h5>We are going to emulate the movement of the Queen which is the strongest piece in Chessboard Game.</br>
</br>
Begin by positioning your cursor within the box and hit click.</h5>
<div id="box">
<div id="Queen" style="font-size: 150%">♛</div>
</div>
// click to move the Queen in chessboard game
var theQueen = document.getElementById("Queen");
var theQueenWidth = theQueen.clientWidth;
var theQueenHeight = theQueen.clientHeight;
console.log("theQueen: " + theQueenWidth + "w x " + theQueenHeight + "h");
//we assign the variables and uses document.getElementById as a function
//to validate and assign the ID which is the "Queen"
document.getElementById("box").onclick = function(event) {
var x = event.layerX - theQueenWidth / 2;
var y = event.layerY - theQueenHeight / 2;
// here we're assigning the "box" as the id with an onclick function since we have to break it down
theQueen.style.top = y + "px";
theQueen.style.left = x + "px";
};
// we have to iterate the x and y
document.onkeyup = function(event) {
var keyIdentifier = getKeyId(event);
console.log(keyIdentifier);
var top = parseInt(theQueen.style.top);
var left = parseInt(theQueen.style.left);
// we are applying parseInt as what we learn from our first assignment
switch (keyIdentifier) {
case "Right":
theQueen.style.left = (left + 1.5 + "px");
break;
case "Left":
theQueen.style.left = (left - .5 + "px");
break;
case "Up":
theQueen.style.top = (top - .5 + "px");
break;
case "Down":
theQueen.style.top = (top + 1.5 + "px");
break;
}
console.log(theQueen.style.top + " x " + theQueen.style.left);
};
// we are using switch function here
function getKeyId(event) {
var keyId = event.keyIdentifier;
if (typeof keyId == "undefined") {
var keyCode = event.keyCode;
switch (keyCode) {
case 39:
keyId = "Right";
break;
case 37:
keyId = "Left";
break;
case 38:
keyId = "Up";
break;
case 40:
keyId = "Down";
break;
}
// in order for the cursor to accurately land on the position desired
return keyId;
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.