Java Reference
In-Depth Information
↵
"violet"];
function change() {
document.body.style.background =
rainbow[Math.floor(7*Math.
↵
random())];
}
button.addEventListener("click", change);
Our first task in the JavaScript code is create a variable called
button
(we cover variables
We then use the
document.getElementById
function to find the HTML element
able.
We now create another variable called
rainbow
. This is assigned to an array containing a
list of strings of different colors (we cover strings and variables in
Chapter 2
and arrays in
background color of the body element to one of the colors of the rainbow (changing the
from the
rainbow
array.
Last of all, we create an
event handler
, which checks for when the button is clicked on.
When this happens it calls the
change
function that we just defined (event handlers are
Open rainbow.htm in your favourite browser and try clicking on the button a few times. If
everything is working correctly the background should change to every color of the rain-
bow, such as in the screenshot in
Figure 1.2
.