|
CogSci 3 |
Introduction to Computing | |||||||||||||||||
|
Sample JavaScript Page #2This is a slightly more interesting use of JavaScript.Again, we have defined a variable, and we will print its current value. But now we will also use that value in a calculation. If we wish to change the value of the variable, we simply do so and new value will be used to in the calculations and produce different results automatically.
For a circle with a radius of , the circumference is while the area would be The embedded JavaScript that created the HTML between the horizontal lines (<HR>) is given below.
<HR>
For a circle with a <I>radius</I> of
<SCRIPT LANGUAGE="JavaScript">
var Radius; // declare a variable called "Radius"
Radius = 7; // set the value of the variable to 7
document.write(Radius); // print out the value right now.
</SCRIPT>
, the <I>circumference</I> is
<SCRIPT LANGUAGE="JavaScript">
// Below, Math.PI is the JavaScript way of referring to the
// mathematic constant PI (3.14159...), and the '*' is
// the JavaScript way of saying "times"
document.write(2 * Radius * Math.PI); // print out the 2 times the value
// times PI
</SCRIPT>
while the <I>area</I> would be
<SCRIPT LANGUAGE="JavaScript">
document.write(Radius * Radius * Math.PI); // print out the value squared
// times PI
</SCRIPT>
<HR>
The JavaScript code is broken up into chucks (between <SCRIPT> and </SCRIPT>) because there is HTML "code" in between the document.write() statements. (The "code" in this example is just some text that we want to appear on the page, but as you can see, it can be/include HTML tags. We've separated it from the <SCRIPT> tags so that you can see it more easily.) So we use </SCRIPT> because we don't want JavaScript trying to interpret the HTML (which would cause a syntax error.). Another way to have done this was to write JavaScript code (e.g., document.write("the <I>circumference</I> is ");) to create the HTML instead of returning to HTML "mode". For example:
<HR>
For a circle with a <I>radius</I> of
<SCRIPT LANGUAGE="JavaScript">
var Radius; // declare a variable called "Radius"
Radius = 7; // set the value of the variable to 7
document.write(Radius); // print out the value right now.
document.write( ", the <I>circumference</I> is " );
document.write(2 * Radius * Math.PI); // print out the 2 times the value
// times PI
document.write( "while the <I>area</I> would be " );
document.write(Radius * Radius * Math.PI); // print out the value squared
// times PI
</SCRIPT>
.
<HR>
Again, this use of JavaScript is not very compelling. But it is a good example of how separate the truly "static" content (the HTML) from the information that might change (the value of the radius and the resulting calculations based on it). I.e., the calculation results depend on the value of the variable "Radius". It also shows you how to generate HTML with document.write(). Terms to Know
|