JavaScript – Client-Side JavaScript

The Window object is the main entry point to all client-side
JavaScript features and APIs. It represents a web browser window or
frame, and you can refer to it with the identifier window. The Window object defines properties
like location, which refers to a
Location object that specifies the URL currently displayed in the
window and allows a script to load a new URL into the

// Set the location property to navigate to a new web page
window.location = "";

The Window object also defines methods like alert(), which displays a message in a
dialog box, and setTimeout(), which
registers a function to be invoked after a specified amount of

// Wait 2 seconds and then say hello
setTimeout(function() { alert("hello world"); }, 2000);

Notice that the code above does not explicitly use the window property. In client-side JavaScript,
the Window object is also the global object. This means that the
Window object is at the top of the scope chain and that its properties
and methods are effectively global variables and global functions. The
Window object has a property named
window that always refers
to itself. You can use this property if you need to refer to the
window object itself, but it is not usually necessary to use window if you just want to refer to access
properties of the global window object.

There are a number of other important properties, methods, and
constructors defined by the Window object. See Chapter 14 for complete details.

One of the most important properties of the Window object is
document: it refers to a Document
object that represents the content displayed in the window. The
Document object has important methods such as getElementById(), which returns a single
document element (representing an open/close pair of HTML tags and all
of the content between them) based on the value of its id attribute:

// Find the element with 
var timestamp = document.getElementById("timestamp");

The Element object returned by getElementById() has other important
properties and methods that allow scripts to get its content, set the
value of its attributes, and so on:

// If the element is empty, then insert the current date and time into it
if (timestamp.firstChild == null)
    timestamp.appendChild(document.createTextNode(new Date().toString()));

Techniques for querying, traversing, and modifying document
content are covered in Chapter 15.

Each Element object has style
and className properties that allow
scripts to specify CSS styles for a document element or to alter the
CSS class names that apply to the element. Setting these CSS-related
properties alters the presentation of the document element:

// Explicitly alter the presentation of the heading element = "yellow";

// Or just change the class and let the stylesheet specify the details:
timestamp.className = "highlight";

The style and className properties, as well as other
techniques for scripting CSS, are covered in Chapter 16.

Another set of important properties on Window, Document, and
Element objects are the event handler properties. These allow scripts
to specify functions that should be invoked asynchronously when
certain events occur. Event handlers allow JavaScript code to alter
the behavior of windows, of documents, and of the
elements that make up those documents. Event handler properties have
names that begin with the word “on”, and you might use them like

// Update the content of the timestamp element when the user clicks on it
timestamp.onclick = function() { this.innerHTML = new Date().toString(); }

One of the most important event handlers is the onload handler of the Window object. It is
triggered when the content of the document displayed in the window is
stable and ready to be manipulated. JavaScript code is commonly
wrapped within an onload event
handler. Events are the subject of Chapter 17. Example 13-1 demonstrates the onload handler and shows more client-side
JavaScript code that queries document elements, alters CSS classes,
and defines event handlers. The HTML <script> element holds the JavaScript
code of this example and is explained in Embedding JavaScript in HTML. Note that the code includes a function
defined within another function. Nested functions are common in
client-side JavaScript, because of its extensive use of event

Example 13-1. Simple client-side JavaScript for revealing content

<!DOCTYPE html>
/* CSS styles for this page */
.reveal * { display: none; }  /* Children of class="reveal" are  not shown */
.reveal *.handle { display: block;} /* Except for the class="handle" child */
// Don't do anything until the entire document has loaded
window.onload = function() {
    // Find all container elements with class "reveal"
    var elements = document.getElementsByClassName("reveal");
    for(var i = 0; i < elements.length; i++) {  // For each one...
        var elt = elements[i];
        // Find the "handle" element with the container
        var title = elt.getElementsByClassName("handle")[0];
        // When that element is clicked, reveal the rest of the content
        title.onclick = function() {
            if (elt.className == "reveal") elt.className = "revealed";
            else if (elt.className == "revealed") elt.className = "reveal";
<div class="reveal">
<h1 >Click Here to Reveal Hidden Text</h1>
<p>This paragraph is hidden. It appears when you click on the title.</p>

We noted in the introduction to this chapter that some web pages
feel like documents and some feel like applications. The two
subsections that follow explore the use of JavaScript in each kind of
web page.

JavaScript in Web Documents

A JavaScript program can traverse and manipulate document
content through the Document object and the
Element objects it contains. It can alter the
presentation of that content by scripting CSS
styles and classes. And it can define the
behavior of document elements by registering
appropriate event handlers. The combination of scriptable content,
presentation, and behavior is called Dynamic HTML or DHTML, and
techniques for creating DHTML documents are explained in Chapters
15, 16, and 17.

The use of JavaScript in web documents should usually be
restrained and understated. The proper role of JavaScript is to
enhance a user’s browsing experience, making it easier to obtain or
transmit information. The user’s experience should not be dependent
on JavaScript, but JavaScript can help to facilitate that
experience, for example by:

  • Creating animations and other visual effects to subtly
    guide a user and help with page navigation

  • Sorting the columns of a table to make it easier for a
    user to find what she needs

  • Hiding certain content and revealing details progressively
    as the user “drills down” into that content

JavaScript in Web Applications

Web applications use all of the JavaScript DHTML features that
web documents do, but they also go beyond these content,
presentation, and behavior manipulation APIs to take advantage of
other fundamental services provided by the web browser environment.

To really understand web applications, it is important to
realize that web browsers have grown well beyond their original role
as tools for displaying documents and have transformed themselves
into simple operating systems. Consider: a traditional operating
system allows you to organize icons (which represent files and
applications) on the desktop and in folders. A web browser allows
you to organize bookmarks (which represent documents and web
applications) in a toolbar and in folders. An OS runs multiple
applications in separate windows; a web browser displays multiple
documents (or applications) in separate tabs. An OS defines
low-level APIs for networking, drawing graphics, and saving files.
Web browsers define low-level APIs for networking (Chapter 18), saving data (Chapter 20), and
drawing graphics (Chapter 21).

With this notion of web browser as simplified OS in mind, we
can define web applications as web pages that use JavaScript to
access the more advanced services (such as networking, graphics, and
data storage) offered by browsers. The best known of these advanced
services is the XMLHttpRequest object, which enables networking
through scripted HTTP requests. Web apps use this service to obtain
new information from the server without a page reload. Web
applications that do this are commonly called Ajax applications and
they form the backbone of what is known as “Web 2.0.” XMLHttpRequest
is covered in detail in Chapter 18.

The HTML5 specification (which, at the time of this writing,
is still in draft form) and related specifications are defining a
number of other important APIs for web apps. These include the data
storage and graphics APIs of Chapters 21 and 20 as well as APIs for a number of
other features, such as geolocation, history management, and
background threads. When implemented, these APIs will enable a
further evolution of web application capabilities. They are covered
in Chapter 22.

JavaScript is more central to web applications than it is to
web documents, of course. JavaScript enhances web documents, but a
well-designed document will continue to work with JavaScript
disabled. Web applications are, by definition, JavaScript programs
that use the OS-type services provided by the web browser, and they
would not be expected to work with JavaScript disabled.[25]

[25] Interactive web pages that communicate with server-side
CGI scripts through HTML form submissions were the original “web
application” and can be written without the use of JavaScript.
This is not the kind of web application that we’ll be discussing
in this book, however.

Comments are closed.