Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
How to loop through a JavaScript array based on key.event?

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!