Start Me Up
To demonstrate some of JavaScript's capabilities, CNET Builder.com has created a Web page that depicts a fictional organization called Adopt-A-Brain. Adopt-A-Brain is an imaginary sponsorship application designed to encourage users to sponsor (or "adopt") homeless brains.
Adopt-A-Brain is by no means a full-scale Web-based application. We streamlined the Adopt-A-Brain's JavaScript so that you can focus on the specific code for each example as it's discussed. To do this, we omitted a lot of the error-checking and automatic calculation code often found in real-life applications. And Adopt-A-Brain doesn't actually send its form data to a server-based program. Still, Adopt-A-Brain offers a useful example of JavaScript, and you can easily extend the Adopt-A-Brain code to incorporate more sophisticated features.
As you go along, you'll notice a See it in action icon--click it to see a pop-up demo of the portion of code being discussed. Instructions in the lower frame tell you what to do.
Before you dive straight into Adopt-A-Brain's code, you need to know the tags for embedding JavaScript into your pages.
<HTML>
<HEAD>
These are the standard tags to start an HTML page. It's good practice to put the JavaScript code between the <HEAD> and </HEAD> tags so that functions don't get called accidentally before the JavaScript is loaded.
<SCRIPT LANGUAGE="JavaScript">
This tells the browser that JavaScript code is about to appear. You may also specify the version of JavaScript in the LANGUAGE attribute, which will cause browsers that do not recognize that version to ignore it. For example, if you specified "LANGUAGE=JavaScript 1.2", any version of Navigator below 4.0 would not process the script.
<!--
This is a safety valve. Everything between the <!-- and the --> below will be ignored by browsers that can't interpret JavaScript.
// put your JavaScript statements below the "//" is a JavaScript comment indicator that tells the browser's JavaScript interpreter to ignore the following text.
function someFunction() {
some JavaScript statements
}
This is where the actual JavaScript goes. The curly braces surround each statement and separate them from other statements in the function. Don't know what a statement is? You will.
// -->
</SCRIPT>
These indicate that we're all done with the script and can go back to HTML code.
</HEAD>
<BODY>
<FORM>
<!-- put your HTML statements below -->
<INPUT TYPE="button" NAME="someButton"
VALUE="Press Me" onClick="someFunction()">
In this case, we tell the browser to run the JavaScript function someFunction() when the user clicks a button.
</FORM>
</BODY>
</HTML>
That's the end of the page. Everything's ready to run when a user loads the page into a JavaScript-ready browser. If you want to cut and paste this template code, click the link.
Next: Checking for Input