- Functions allow us to write a chunk of code once that can be reused over and over.
changeColor(). This function chooses a color from a list of colors.
How does that happen?
getRandomColor() function generates a random series of numbers and letters to create a new hexadecimal color code.
It then saves the new color under the name
let newColor = getRandomColor();
On the next line, the
document keyword accesses the page’s background color and sets it equal to the new color.
document.body.style.backgroundColor = newColor;
Click the Run button to move on to the next checkpoint to see how we can let a user change the color!
The next step is to connect the
Repaint! button, it changes the background color.
An event is something that can happen in a browser, like clicking or hovering with your mouse.
In this case, the name of the event is
onclick and we can invoke the function by calling
Paste this code into the opening tag of the button element:
Let’s test out the functionality of the code that we just added. When you click the “Repaint!” button, the background color of the site should be reset at random!
When you’re ready, click Run again and move on to the next exercise.