skip to Main Content

I’m working on a program that aims to use an array of colors (that are stored as strings). I need to take the strings and change the color of a piece of text to a random color.

Sample Array:
let colorArray = ["red", "blue", "green", "purple"];

My Function:

// "introduction" refers to the piece of HTML that is being changed
function onClickIntro()
{
    //returns a color from a random index in colorArray
    return introduction = colorArray[Math.floor(Math.random() * colorArray.length())];
}

My goal is to use the strings from the array to change the color of a piece of HTML text. I’ve gotten nothing so far.

2

Answers


  1. You’re almost there.

    Building on what you already have so far, you can apply the color, via:

    // "introduction" refers to the piece of HTML that is being changed
    function onClickIntro() {
      let newColorIndex = Math.floor(Math.random() * colorArray.length);
      let newColor = colorArray[newColorIndex];
      introduction.style.setProperty('color', newColor);
    }
    

    Further Reading:

    Login or Signup to reply.
  2. You have to get the element that you want to change the color using getElementById, getElementsByClassName or the way you find useful for your code and change its style properties color or background:

    function onClickIntro() {
      let element = //you get here the element you want to change its colors
      //Careful, .length is property, not a function()
      let randomIndex = Math.floor(Math.random() * colorArray.length); 
      element.style//.property you want to change = colorArray[randomIndex];
    }
    

    Full example (use only if you get stuck after trying hard or after finishing your program)

    Happy coding!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search