Move the Queen

by Angeli Schwartz

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Move the Queen in Chess</title>
</head>
<body>
<div id="box">
<div id="Queen">♛</div>
</div>
</body>
</html>

CSS

#box {
  border: solid gray 3px;
  font-size: 30px;
  width: 100%;
  height: 300px;
  position: absolute;
}
#Queen {
  color: #996633;
  position: absolute;
    
}

JavaScript

// 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;
  
      
  }
};