Java Reference
In-Depth Information
function change() { =
button.addEventListener("click", change);
Our first task in the JavaScript code is create a variable called button (we cover variables
in Chapter 2 ) .
We then use the document.getElementById function to find the HTML element
with the ID of button (covered in Chapter 6 ) . This is then assigned to the button vari-
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
Chapter 3 ) .
Then we create a function called change (we cover functions in Chapter 4 ). This sets the
background color of the body element to one of the colors of the rainbow (changing the
style of a page will be covered in Chapter 6 ) . This involves selecting a random number us-
ing the built-in Math object (covered in Chapter 5 ) and selecting the corresponding color
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
covered in Chapter 7 ) .
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 .
Search WWH ::

Custom Search