Chapter 3. JavaScript
JavaScript is a programming language that browsers can execute, used for defining a page's behavior, particularly in response to user events. The name is simply a marketing gimmick: It is hardly based on Java at all, but rather on C.
3.1. Hello world
Because of the wide variety of browsers, working with bare JavaScript is a frustrating chore: The features common to all are rather limited, and even among the common features are frustrating incompatibilities. But there is a simple workaround: Incorporate a third-party library called a JavaScript framework that papers over the incompatibilities and adds additional features. While there are many JavaScript frameworks available, we'll study the most popular among them, called jQuery.
Let's start with a very simple example. Below is a simple HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Beginning JavaScript</title>
</head>
<body>
<p id="hi"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="hello.js"></script>
</body>
</html>
You can see toward the end two <script>
elements.
Each tells the browsers to load a file from the Web
and to execute the JavaScript code in it.
The first of the two files is the jQuery library, which we're
telling the browser to load from Google's site
(so that our server doesn't have to spend its time on it).
The second is hello.js, which holds the following:
function putGreeting() {
var p_hi;
p_hi = $('#hi');
p_hi.text('Hello world!');
}
$(document).ready(putGreeting);
You'll notice two instances of $
in this code.
These are references to the jQuery library. You see, jQuery
wants to avoid adding lots of names, since this inevitably leads
to conflicts with other code that people might have written. But
they wanted to choose a short name since programs using jQuery
tend to reference it frequently.
Thus, looking for a short variable name that others are unlikely
to use, jQuery chose to nest all
of its functionality into a function named $
.
You can see that
hello.js has two parts — the definition of a function
named putGreeting
and a rather odd final line.
Let's look at that final line first.
This is jQuery's rather odd way of scheduling a function to be
invoked once the page is fully loaded. You see, browsers
often execute JavaScript code while still in the process of loading
and processing the HTML. Our code will access the HTML
structure, so it shouldn't execute until the browser has
interpreted it. We use the “$(document).ready
”
function to schedule something to be executed at that time.
Inside the parentheses on that final line you see putGreeting
.
This is the name of the function to be invoked once the page is loaded.
Notice that it does not say putGreeting()
!
Adding parentheses after a function name says to call it:
We'd be saying to call the putGreeting
function immediately (and to schedule the value returned by
putGreeting
to be invoked once the page is loaded).
But as we wrote the code, the browser will enter the putGreeting
function once the page is ready. This function has three lines:
The first line of
putGreeting
simply declares a variable: You can't associate types with variables in JavaScript, but you should declare that they exist using thevar
keyword.The second line of
putGreeting
passes a string into jQuery's$
function. When you give$
a string, jQuery understands the string as a selector and goes through the Web page to find matching elements; in our case, it will look for an element whose identifier is hi. The$
function will return an object that is essentially a set of all the elements it found, and our code associates the namep_hi
with this set.And finally, the third line invokes
p_hi
'stext
method. Given a string parameter, this jQuery method changes the element so that it contains that text. Consequently, while in the initial HTML file, the<p>
element is empty, the JavaScript places the words “Hello world!” into it, and the user will see:Hello world!
Of course, we could have simply written this text directly into the HTML file, without using JavaScript at all. But we have to start somewhere!
3.2. User interaction
Now let's look at a slightly more impressive example,
which allows the user to enter a name. Below is what belongs in
the HTML <body>
element.
(We'll stop repeating the other boilerplate structure from now on.)
<p>Your name:
<input id="who"></input>
<button id="done">Submit</button></p>
<p id="hi"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="hello.js"></script>
When this page is loaded, we see the following:
Your name:
We'll now write our JavaScript file hello.js so that when the user clicks the Submit button, the name typed into text field is incorporated into a greeting for the user.
function putGreeting() {
var field, name, p_hi;
field = $('#who');
name = field.val();
p_hi = $('#hi');
p_hi.text('Hello ' + name + '!');
}
function configureSubmit() {
var b;
b = $('#done');
b.click(putGreeting);
}
$(document).ready(configureSubmit);
At the bottom, you can see that we schedule
configureSubmit
to be invoked once the HTML document is
loaded. The configureSubmit
function retrieves the
element whose identifier is done, and using the
jQuery method click
it schedules putGreeting
to
be invoked whenever the button is clicked.
When this happens, the putGreeting
function retrieves the
input field (whose identifier in the HTML is who),
uses its val
method to pull the value typed into the field,
and then incorporates that text into the text placed into the
element whose identifier is hi.
3.3. Anonymous functions
You can see that as we build up longer programs, we can quickly get lots of functions with rather convoluted names. In practice, we end up using anonymous functions quite a bit. JavaScript allows us to write a function without giving it a name, using it as part of an expression. For example, we might write the following:
$(document).ready(function () {
$('#done').click(putGreeting);
});
Inside the ready
function we've passed an anonymous
function as a parameter. This anonymous function takes no
parameters itself, and when invoked it sets up the button named
done to invoke putGreeting
whenever it is
clicked. Rather than define a configureSubmit
function
as before, we've incorporated its definition into ready
's
parameter.
We can repeat the process to avoid defining the
putGreeting
function.
$(document).ready(function () {
$('#done').click(function () {
var name;
name = $('#who').val();
$('#hi').text('Hello ' + name + '!');
});
});
Expert jQuery programmers use anonymous functions heavily, so this is an entirely typical example of a simply jQuery program.
3.4. Exercise: Distance conversion
Why don't you take a crack at it? Try writing a simple page for converting between kilometers and miles. (Remember that there are roughly 1.61 kilometers to a mile.) Your page might appear similar to the following:
Kilometers:
Miles: 16.1