Javascript Tutorial - Lesson 1 High-LowA function is a sequence of instructions that are executed when the function is called. It is defined as follows:
Following is an example program along with HTML Form elements to illustrate Javascript programming: | ||
| Javascript statements | Comments | |
<script language="javascript">
var g,minimum,maximum;
function start(){
minimum=1;
maximum=100;
g=minimum-1;
too_low();}
function too_low(){
minimum=g+1;
g=Math.floor((minimum+maximum)/2);
document.formg.guess.value=g;}
function too_high(){
maximum=g-1;
g=Math.floor((maximum+minimum)/2);
document.formg.guess.value=g;}
function correct(){
document.formg.guess.value=g+" is correct";}
</script>
|
Introduces a section of Javascript declare labels for variables declares a function called start() sets the variable minimum to 1 sets the variable maximoum to 100 sets initial value for g to minimum -1 call the function too-low() declares a function called too_low() sets the minimum to the last guess (g) + 1 computes a new guess halfway between minimum & maximum outputs it to the guess textbox declares a function called too_high() sets the new maximum to the last guess (g) - 1 computes a new guess halfway between minimum & maximum outputs it to the guess textbox declares a javascript function called correct() outputs the message that g is the correct guess terminates Javascript section | |
| HTML | Comments | |
<form name="formg"> <input type=text name=guess size=24 value=""><br> <input type=button value="Start" onClick="start();"> <input type=button value="Too low" onClick="too_low();"> <input type=button value="Too high" onClick="too_high();"> <input type=button value="Match" onClick="correct();"> </form> |
declares a form called formg defines a textbox called guess defines a button that calls start() defines a button that calls too_low() defines a button that calls too_high() defines a button that calls correct() defines the end of formg |
|
Homework Assignment | ||