JavaScript is most commonly used by web browsers to dynamically create
and modify web pages.
Web pages are formatted using the
HyperText Markup Language
(HTML, which we describe in the section
HTML and the DOM).
When an HTML page is rendered by a browser, an object-oriented model of
the page, called a
Document Object Model (DOM), is maintained
behind the scenes.
If JavaScript code is embedded in a web page, it has access to the DOM
and can manipulate it.
We can exploit this to set up a simple JavaScript testing environment
using any modern web browser and file editor.
NetBeans makes a convenient environment for developing and testing
JavaScript code.
- Click File and then New Project...
- In the dialog, under Categories choose HTML/JavaScript and
under Projects choose HTML5 Application
- Give your project a name and location, then click through the
remaining defaults
An HTML file called
index.html will be created under
Site Root.
To create a new HTML or JavaScript file:
- Right-click Site Root
and choose New -> HTML File... or JavaScript
File... to get a file creation dialog
HTML pages are made up of
elements.
A typical element has the form:
<element> ... </element>
where
element is one of a number of pre-defined HTML
"
tags" that describe the structure of a web page.
<element> is called the "
open" tag for the element;
</element> is called the "
close" tag.
Anything between an element's open tag and close tag ("
..."
above) is part of the element's
body.
HTML is described in more detail in
HTML and the DOM.
A special HTML element is
script, which allows web pages to have
JavaScript code.
For the purposes of testing simple JavaScript, an HTML page need only
have a
script element with code in its body. Suppose you have
created the file
fact.html in NetBeans with these contents:
When a browser renders this page, it will execute the JavaScript code.
You can view the browser's rendering of this page from NetBeans
by right-clicking
fact.html and selecting
Run File.
- Note: To make sure any changes you've made to the file are saved before
viewing, you can "Clean" the project.
However, nothing is done with the value of the "
fact(5)"
expression and so the page will be blank.
The simplest way to output data from a JavaScript program is through
the built-in
alert method:
alert(message);
where
message is any object with a string representation.
alert pops up message dialogs much like
Java's
JOptionPane.showMessageDialog methods:
Here is how a browser renders this page:
fact2.html.