skip to Main Content
function initvkeyboard(){
                var chars = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",]
                for(var i = 0; i < chars.length; i++){
                    $("#kbtnlist").append("<div class='kbtn' onclick=typechar('"+chars[i]+"')>"+chars[i]+"</div>")
                }
            }

I am making a crossword game this is a javascript function which accepts the input from the popup and displays it. Instead of it i want to give keyboard access to this game how do i make this function to get user input instead from my keyboard and not print the popup

function initvkeyboard(){
    Window.location = ""+ input.value;

    for(var i = 0; i<input; i++){
        $("#kbtnlist").append("<div class='kbtn' onclick=typechar('"+chars[i]+"')>"+chars[i]+"</div>")
    }
}

this is what i am trying to do i want to give keyboard access to my crossword game and not give popup

2

Answers


  1. You could add a key-down listener on the document level:

    document.addEventListener("keydown", function (e) {
        if (e.key.length == 1 && e.key >= "a" && e.key <= "z") {
            typechar(e.key);
        }
    });
    

    Here is a demo:

    document.addEventListener("keydown", function (e) {
        if (e.key.length == 1 && e.key >= "a" && e.key <= "z") {
            typechar(e.key);
        }
    });
    
    // The function you did not provide, so this is just a demo
    function typechar(key) { 
        const output = document.getElementById("typearea");
        output.textContent += key; 
    }
    Click on this area and then start typing:
    <div id="typearea"></div>
    Login or Signup to reply.
  2. You can add an event listener to the document to capture keyboard input. Then you can check if the pressed key is a letter (a-z) and then call your typechar function.

    Here is the updated code:

    function initvkeyboard() {
      document.addEventListener("keydown", function (event) {
        if (event.keyCode >= 65 && event.keyCode <= 90) {
          var char = String.fromCharCode(event.keyCode).toLowerCase();
          typechar(char);
        }
      });
    
      var chars = [
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
        "g",
        "h",
        "i",
        "j",
        "k",
        "l",
        "m",
        "n",
        "o",
        "p",
        "q",
        "r",
        "s",
        "t",
        "u",
        "v",
        "w",
        "x",
        "y",
        "z",
      ];
    
      for(var i = 0; i<input; i++){
        $("#kbtnlist").append("<div class='kbtn' onclick=typechar('"+chars[i]+"')>"+chars[i]+"</div>")
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search