I'm a newbie messing around with event listener/handlers and generally just getting to grips with some JS (first post on StackOverflow!)
I'm making a simple webpage that changes backgroundColor based on user input (alpha characters only). The user presses a letter key and the page will update to a color with a match on the first letter. It will also print the name of the color to the page.
I have a large array storing names of CSS colors, most keys have multiple colors that match the keystroke/first letter of the color, and some keys have no matches.
My code below hopefully explains my intentions, however I can't quite get it to work.
const colors = ["Aquamarine", "Alice Blue", "Antiquewhite", "Aqua", "Azure"] etc etc...
// Returns a random colour from the colour arrays
const randomiser = colorArr => {
return colorArr[Math.floor(Math.random()*colorArr.length)];
}
// Event listener
window.addEventListener("keypress", e => {
let colorsMatchingKeyName = [];
function colorFinder(arr) {
let keyName = e.key;
for (let i = 0; i < arr.length; i++) {
if (arr[i].charAt(0) !== keyName) {
document.getElementById('currentColor').innerHTML = `Sorry! No colours match up with the ${keyName} key!`;
} else if (arr[i].charAt(0) == keyName) {
colorsMatchingKeyName.push(arr[i]);
}
}
}
colorFinder(colors);
// Logging colors to console to test.
console.log(colorsMatchingKeyName) // outputs an empty array
// Once it is working i'll use the randomiser() function to pick a
// random colour from the colorMatchingKeyName array and set the document.style.backgroundColor
})
At present, each key event only prints the 'Sorry! No colours...' message shown in the if statement.
I'd be hugely grateful if someone could please direct me to the issue in my code!
You might want to check this out:
const colors = ["Aquamarine", "Alice Blue", "Antiquewhite", "Aqua", "Azure"]
// Returns a random colour from the colour arrays
const randomiser = colorArr => {
return colorArr[Math.floor(Math.random()*colorArr.length)];
}
// Event listener
window.addEventListener("keypress", e => {
let colorsMatchingKeyName = [];
function colorFinder(arr) {
let keyName = e.key;
document.getElementById('currentColor').innerHTML = '';
for (let i = 0; i < arr.length; i++) {
const c = arr[i].charAt(0).toLowerCase();
if (c !== keyName.toLowerCase()) {
document.getElementById('currentColor').innerText = `Sorry! No colours match up with the ${keyName} key!`;
} else if (c == keyName) {
colorsMatchingKeyName.push(arr[i]);
}
}
}
colorFinder(colors);
const color = randomiser(colorsMatchingKeyName);
console.log(color)
document.body.style.backgroundColor = color;
})
<div id="currentColor"></div>