bbb Home |
Lesson 7 - Program Start Button |
SUMMARYIn this lesson you will program the start button to respond to the click event. You will learn to write and call functions. You will also learn to use an alert. DISCUSSIONIn this lesson we will add code to the game page to make the start button respond to the click event. While we could add code directly to the onclick event, we are going to learn to use functions. A function is a set of statements that performs a task. To use functions you must understand the concepts of defining and calling a function. When you define a function, you are defining the name of the function and the statements that the function does. Just because a function is defined does not mean that it will execute. To execute the function you need to call it. We define a function in a <script> block as follows: function functionName(){ Statements go here } You must use the function word, the parentheses after the function name, and the brackets to enclose the set of statements. You must also give the function a name. The name should describe what the function does and meet the following conditions:
When you call a function you type in the name of the function followed by the parentheses. The use of functions offers the following benefits:
The benefits of functions will become moe apparent as you learn to program. There are many functions built into JavaScript. One of the these is the alert. When you use an alert, a message box will appear with a message in it. In this game program we will use an alert at the end of the game to inform the user that the game is over. We will also use alerts to test our program as we write it. These alerts will be removed from the program as we add code. The example below shows how to create and call a function. Lines 4 to 7 define the function. The function is called showAlert() and does two things. The statement on line 5 makes an alert appear with the word "hi" in it. The statement on line 6 changes the background color of the document to red. In line 11, the function is called when the user clicks on the <div>. EXAMPLE - Functions and Alert
PRACTICEIn the example above:
GAME DEVELOPMENTModify your game page (game.htm) as follows:
|
References |
©dfx interactive, inc. Contact us at bigbadbrain@bigbadbrain.com |