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"; }
Advertisement
Answer
Why not check for a range of keys:
document.addEventListener('keydown', function(event) { if (event.key >= 'a' && event.key <= 'z'){ console.log(event.key); }