This Lesson, I thought I'd focus on the previously neglected processing aspect of Javascript. The mathematical functions are pretty straight forward and can be found nicely laid out here:
Math FunctionsIt is important to note that these methods and constants are part of what is called the Math object so they must be called using the object name followed by a dot then the function or constant as in the following example which uses the pow function and the PI constant:
<HTML>
<HEAD>
<SCRIPT TYPE="text/javascript">
function findArea()
{
var radius=prompt("What\'s the area of your circle?",1);
alert(Math.pow(radius,2)*Math.PI + " is the area of your circle.")
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT TYPE="button" ONCLICK="findArea()" VALUE="Area">
</BODY>
</HTML>
(BTW if I get too simple for you, like just then with the dot-notation explanation, it is because you never know who might also want to go through this without your background.)
And then we go on to string manipulations which include text formatting as well as traditional string functions again found here:
These are a little different because the object name you use with them is the name of a string variable you wish to perform them on as in the following example using the replace function on a string object I called buttonLabel:
<HTML>
<HEAD>
<SCRIPT TYPE="text/javascript">
function replaceText()
{
var newText=prompt("What do you love better than chocolate?","Mother");
var buttonLabel=document.getElementById("Button1").value;
var newLabel=buttonLabel.replace(/Chocolate/,newText);
document.getElementById("Button1").value=newLabel
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT TYPE="button" ID="Button1" ONCLICK="replaceText()" VALUE="Click here if you love Chocolate">
</BODY>
</HTML>
That was a bit hard to explain but specifically, I wanted to replace the word "Chocolate" in the button label (Value) with whatever the user typed. So first I got the user's input and placed it in the variable "newtext". Then I read the button label into a variable called "buttonLabel". Then I replaced the word "Chocolate" with whatever the user typed and assigned it to the variable "newLabel". That is where the replace function came into it. Lastly, I assigned the new label as the new value of the button.
There is one exception in the String list and that is fromCharCode which is a function of the String object and is called as in the following example:
<HTML>
<BODY>
<SCRIPT TYPE="text/javascript">
document.write(String.fromCharCode(65,66,67,68,69,70))
</SCRIPT>
</BODY>
</HTML>
Play around with the math and string functions. It could take a long while to explore them all. But I won't give an actual project until after the next lesson.