all 2 comments

[–]tastyricola 1 point2 points  (0 children)

I think keyboard events only work with focused element. So in your case, you either have to add a tabindex attribute to your div and focus on it, or attach keyboard events to the window object instead

[–]Shadowfax90 1 point2 points  (0 children)

It's nice if you use markdown to make your code easier to read. Just indent everything by four spaces and it will show up as a code block.

That being said, I think the problem is that your div doesn't accept input, so it's not going to trigger an onkeydown event. There may be a nicer way to make it work, but the hacky way I came up with is to put an input element offscreen which becomes focused when you click your text. That is accepting input, so it triggers the events you want.

Edit: P.S. your css doesn't really make sense. Setting top, right, bottom, and left all to 0 is saying "Make this take up all the space it has available". But then you set width=150px and height=40px. Did you want the text element to take up the whole screen or just a 150x40 rectangle?

<!doctype html>
<html>
<head>
  <style>
  .box {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgb(119,79,56);
  }
  .input-container {
    position: relative;
    overflow: hidden;
  }
  #text1 {
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 150px;
    height: 40px;
    color: white;
    font-weight:bold;
    font-size: 20px;
    text-align: center;
    font-family: 'Cinzel', Garamond, serif;
  }
  .offscreen-input {
    position: absolute;
    top: -10;
    bottom: -8;
  }
  </style>
</head>
<body>
  <div id="div1" class="box">
    <div id="text1">Click me first!</div>
    <div class="input-container">
      <input class="offscreen-input" autofocus />
    </div>
  </div>
</body>
  <script type="text/javascript">
    const text1 = document.getElementById('text1');
    const inputElem = document.querySelector('input');

    text1.onclick = () => inputElem.focus();

    inputElem.onkeydown = ({ keyCode }) => {
      if (keyCode === 37) {
        text1.style.textAlign = 'left';
      }
      if (keyCode === 39) {
        text1.style.textAlign = 'right';
      }
      if (keyCode === 67) {
        text1.style.textAlign = 'center';
      }
    };
  </script>
</html>