JavaScript Functions

To keep the browser from executing a script when the page loads, you can put your script into a function.

A function contains code that will be executed by an event or by a call to that function.

You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file).

Alert Box

An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax:

alert("sometext")

Confirm Box

A confirm box is often used if you want the user to verify or accept something.

Arithmetic Operators

Operator Description Example Result
+ Addition x=2
y=2
x+y
4
- Subtraction x=5
y=2
x-y
3

The JavaScript Switch Statement

You should use the switch statement if you want to select one of many blocks of code to be executed.

Variables

A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value.

Rules for variable names:

  • Variable names are case sensitive
  • They must begin with a letter or the underscore character

IMPORTANT! JavaScript is case-sensitive! A variable named strname is not the same as a variable named STRNAME!

JavaScripts in the body section will be executed WHILE the page loads.

JavaScripts in the head section will be executed when CALLED.


Where to Put the JavaScript

JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.


How to Put a JavaScript Into an HTML Page

[<]html[>]
[<]body[>]
[<]script type="text/javascript"[>]
document.write("Hello World!")
[<]/script[>]
[<]/body[>] [<]/html[>]

The code above will produce this output on an HTML page:

JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more.

JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and Opera.


What You Should Already Know

Before you continue you should have a basic understanding of the following:

  • HTML / XHTML