Search code examples
keyboard-eventskey-bindings

How to add arrow keybinding to react\redux


Finally i have created a game , It's a 3 answers quiz game, but I want to be able to scroll through the 3 answers, which are 3 buttons, with my up and down keys. but I've been struggling on how to implement it, does anyone tried this before? or any tips?

This is my dummy code to add to my redux, but it's not very functional

<!DOCTYPE html>
<html>

<head>
  <style>
    a:focus, a:active {
    font-size: 18px;
    color: red;
    font-family: Helvetica;
    }

   .btn:focus {
     background: green;
     outline: none;
   }
</style>
</head>

<body onkeydown="myFunction(event)">

  <a id="myAnchor" href="https://www.w3schools.com">Visit W3Schools.com</a>

  <p id="demo"></p>

  <input class="btn" id="btn-1" type="button"  value="First dog">
  <input class="btn" id="btn-2" type="button"  value="Second dog">
  <input class="btn" id="btn-3" type="button"  value="Third dog">

  <script>
    window.onload = () => {
      document.getElementById("btn-1").focus();
      console.log(document.activeElement)
    };

    function myFunction(event) {
      const btn1 = document.getElementById("btn-1");
      const btn2 = document.getElementById("btn-2");
      const btn3 = document.getElementById("btn-3");

      const keyPress = event.which || event.keyCode;
      const focusedButtonElement = document.activeElement.id

      switch(focusedButtonElement) {
        case "btn-1":
          if (keyPress === 39) return btn2.focus() 
        case "btn-2":
          if (keyPress === 37) return btn1.focus() 
          if (keyPress === 39) return btn3.focus() 
        case "btn-3":
          if (keyPress === 37) return btn2.focus() 
        default:
        break
      }

      if(keyPress === 13) {
        document.activeElement.click();
        console.log("clicked")
      }

    }
  </script>

</body>

</html>

Thanks guys


Solution

  • Remove the onkeydown event listener from body tag, and modify window.onload function to add the event listener programmatically.

    window.onload = () => {
        document.getElementById("btn-1").focus();
        console.log(document.activeElement)
        document.addEventListener('keydown');
    };