// click to move the Queen in chessboard game
document.getElementById("box").onclick = function(event){
console.log(event);
// layerX and layerY are good for getting the x/y of the div
// not the page, not the body
var x = event.layerX;
var y = event.layerY;
var theQueen = document.getElementById("Queen");
// concatenating the "px" is important
// top and left are strings, not numbers
theQueen.style.top = y + "px";
theQueen.style.left = x + "px";
};
// up down left right to move an X
// note that I attached the keyup listener to the document
// if you have questions about the implications of this,
// let me know ;)
document.onkeyup = function(event){
var theQueen = document.getElementById("Queen");
console.log(event);
// switch statements aren't all that common anymore
// they're just out of vogue, but they can be useful
switch(event.keyIdentifier){
case "Right":
var newQueen = parseInt(theQueen.style.left) + .5;
theQueen.style.left = newQueen + "px";
break;
case "Left":
var newQueen = parseInt(theQueen.style.left) - .5;
theQueen.style.left = newQueen + "px";
break;
case "Up":
var newQueen = parseInt(theQueen.style.top) - .5;
theQueen.style.top = newQueen + "px";
break;
case "Down":
var newQueen = parseInt(theQueen.style.top) + .5;
theQueen.style.top = newQueen + "px";
break;
}
};
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.