![]() |
|
|||||||
| Technology Computing, programming, science, electronics, telecommunications, etc. |
|
|
Thread Tools | Display Modes |
|
|
#33 |
|
I am meaty
Join Date: Dec 2001
Location: Salt Lake City, UT
Posts: 1,119
|
Ok, on to Functions. If you want to create a function, you use the function keyword. Like with var, the function keyword is then followed by the function name. Then, you include a list of arguments in parethases (we'll get to this in a bit), and then the block of code which will execute when a call is made to this function.
Here's a simple example, using some code from a previous example: Code:
function changeBackgroundColor () {
var prompt = "Click OK to change the background to red.\nClick Cancel to make it blue.";
if (confirm(prompt)) {
document.bgColor = "red";
}
else {
alert("We'll make it blue then.");
document.bgColor = "blue";
}
}
Code:
changeBackgroundColor(); Now let's modify it to accept arguments. When we create the function with the function keyword, if we define arguments in the parenthases, then we can pass information to the function for it to work with. Here's an example: Code:
function changeBackgroundColor (prompt, newColor) {
if (confirm(prompt)) {
document.bgColor = newColor;
}
}
Code:
var colorPrompt = "Click OK to change the background color.\nClick Cancel to leave it unchanged."; var color = "purple"; changeBackgroundColor(prompt, color); Code:
changeBackgroundColor ("Do you want to change the background color?", "green");
Code:
function addTwoNumbers (first, second) {
var sum = parseInt(first) + parseInt(second);
return sum;
}
Code:
var someNumber = prompt("Enter any number");
var anotherNumber = prompt("Enter any other number");
var myTotal = addTwoNumbers(someNumber, anotherNumber);
alert(myTotal);
Suppose the user leaves the entry fields blank when they run this script. The prompt() function would return an empty string (""), and the call to addTwoNumbers() would fail, because there are no numbers to add. If we wanted to be cautious in our programming, and make sure the user didn't provide an empty string, we can test for that in the function, and provide an error if necessary: Code:
function addTwoNumbers (first, second) {
if (first == "") {
alert("You didn't provide the first number");
return 0;
}
if (second == "") {
alert("You didn't provide the second number");
return 0;
}
var sum = parseInt(first) + parseInt(second);
return sum;
}
More later...
__________________
Hot Pastrami! |
|
|
|
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|