Home > Software design >  Would there be a shorter version of this part of code in JS / CSS / HTML programming?
Would there be a shorter version of this part of code in JS / CSS / HTML programming?

Time:05-27

A question in JS / CSS / HTML programming!

Again, I'm not good at asking the question pinpoint, and sorry for all the confusion. I shall talk about my real intention for this part of code, and see what solutions can be made.

I'd like to invite the users to input characters, which will be thrown into part of the variable characters for another function create_random_string().

If that's the case, what solutions can be made to shorten the code for the part document.addEventListener() for the sake of efficiency? Thank you very much!

var characters = '';
function create_random_string(string){
  var random_string = '';
  for (var i, i = 0; i < string; i  ) {
     random_string  = characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return random_string; 
} 

document.addEventListener('keydown', function(event) {
  if(event.key == "a") {
    characters  = "a";
  }
  else if(event.key == "b") {
    characters  = "b";
  }
  else if(event.key == "c") {
    characters  = "c";
  }
...
  else if(event.key == "x") {
    characters  = "x";
  }
  else if(event.key == "y") {
    characters  = "y";
  }
  else if(event.key == "z") {
    characters  = "z";
  }

CodePudding user response:

Why not check for a range of keys:

document.addEventListener('keydown', function(event) {
  if (event.key >= 'a' && event.key <= 'z'){
    console.log(event.key);
  }

CodePudding user response:

e is Event Object. .key is an Event property that gets the key that was tapped. When testing a key event make sure to click the testing area to gain focus first.

document.onkeydown = logKey;

function logKey(e) {
  console.log(e.key);
}

CodePudding user response:

One way to do this that's even shorter than the other answers:

document.onkeydown = (e) => console.log(e.key);

This uses an inline function to further reduce the length of the answer by zer00ne.

If you are more interested in form validation than just logging to the console, you can also do something along the lines of the following:

function alphaOnly(event) {
  let key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};
  • Related