0

When I click on the arrow keys, it appears that the console notices that the keys are being pressed but it doesn't respond by moving the object I want to move. It has an issue reading "x" and "z". For example, the console states: "Uncaught TypeError: Cannot read properties of undefined (reading 'x') at HTMLDocument.document.onkeydown".

Please check out my code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Practice</title>

<style> 

 ...
.purp {
  background-color: violet;
  width: 250px;
  text-align: center;
  padding: 5px;
  border: 5px solid aqua;
  float: left; 
}
... 

</style> 

<script> 
 
var purp = document.getElementsByClassName ("purp");

document.onkeydown = function (move) {
  if (move.keyCode == 37) {
    purp.position.x -= 1; 
  }
  else if (move.keyCode == 39) {
    purp.position.x += 1;
  }
  else if (move.keyCode == 38) {
    purp.position.z -= 1;
  }
  else if (move.keyCode == 40) {
    purp.position.z += 1;
  }
};

</script>
</head>

<body>
 
...
<side-menu class='purp'>
  <div>
    <h2>ngfsndkgnsdkfng</h2>
    <p>fdkmgsdlfgmdflkggelkgdlfkmgdlkf</p>
    <p>dfgjdgorkgjeogmoggkmdlfkbmsdkgfmkfmgkggkn</p>
  </div>
</side-menu>
...

</body>
</html>
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Jennifer
  • 21
  • 3
  • Question tags have been edited and the [tag:Java] tag has been removed. I see no Java here. Please let me know if I am missing something. – Hovercraft Full Of Eels Feb 06 '22 at 12:48
  • 1
    Neither `HTMLCollection`s not `NodeList`s have a `position` property. – Sebastian Simon Feb 06 '22 at 12:49
  • @SebastianSimon Hey, Sebastian. I gave my HTML a position by linking the class "purp" so I can move that object. Seems like I'm missing something, though? Also, I'm new to coding btw. Could you explain to me what that means, please? What would I have to change or add, exactly? – Jennifer Feb 06 '22 at 14:51
  • @Jennifer _“I gave my HTML a position by linking the class `purp`”_ — Where do you do this? Have you read the linked post? A collection of elements is not an element itself. `document.getElementsByClassName("purp")[0]` is an element. `document.querySelector(".purp")` is an element. `document.getElementsByClassName("purp")` is _not_ an element. – Sebastian Simon Feb 06 '22 at 15:32

0 Answers0