The JavaScript Diaries: Part 4 - Page 2
[previous] [next]
The JavaScript Diaries: Part 4
Let's create a function and see how it works. First, we'll declare the function so we can load it into memory:
<script type="text/javascript"> <!-- function music() { var place="Delta"; var type="blues"; document.write("I like " + place + " " + type + "."); } //--> </script>
Next, we call the function:
<script type="text/javascript"> <!-- music(); //--> </script>
Once the call is made, the JavaScript interpreter checks to see if the function has been loaded into memory. In our example above, it's already loaded because it came before the function call. Once the JavaScript interpreter finds the function, it proceeds to execute the code contained within the curly brackets. In this case, the code is executed as follows:
|
This time we'll try doing the same thing with a few changes. We'll change the document.write
command to an alert
command and we'll call it from within the function itself. (Be sure to try this out yourself.)
<script type="text/javascript"> <!-- function music() { var place="Delta"; var type="blues"; alert("I like " + place + " " + type + "."); } music(); //--> </script>
You can even call it from within a link (thanks to Andrew and Jonathan Watt). Put this code in the <head>
portion:
<script type="text/javascript"> <!-- function greetVisitor() { var myName = prompt("Please enter your name.", ""); alert("Welcome " + myName + "!"); } //--> </script>
Then, add this link somewhere in the body of the page and click on it:
<form> <input type="button" value="Click for Greeting" onClick="greetVisitor();"> </form>
Here's one that provides a solution if a name is not entered. It uses a conditional statement and some of the operators were studied in the previous release of the JavaScript Diaries:
Place this in the <head>
portion:
<script type="text/javascript"> <!-- function greetVisitor() { var myName = prompt("Please enter your name.", ""); if ( (myName == "") || (myName == null) ) { alert("Don't you even know your own name?"); } else { alert("Welcome " + myName + "!"); } } //--> </script>
Then, put this in the <body>
portion:
<form> <input type="button" value="Click for Greeting" onClick="greetVisitor();" </form>
Be sure to try it out all three ways: putting in your name; pressing "OK" without putting in your name and pressing cancel.
This one is fairly simple:
|
For those of you who have forgotten, null
is a "built-in" variable that does not have a value. It does not return a zero or a space. It's usefulness is seen above, for testing purposes.
[previous] [next]
Created: May 27, 2005
URL: