An Algorithmic and Social Introduction to Computer Science (CSC-105 2000S)


Class 21: Introduction to JavaScript

Back to Computer Viruses. On to Lab: Introduction to JavaScript.

Held Monday, February 28, 2000

Overview

Today we begin to study JavaScript, a programming language for the World Wide Web.

Question 22 for Tuesday's class: Describe an algorithm that you think would be useful for the Web.

Notes

Contents

Summary


Programming for the World-Wide Web

Introduction to JavaScript

JavaScript is a programming language developed by Netscape Communications Corporation to permit more interactive HTML pages. Why do we need JavaScript? HTML, the core language of the World-Wide Web, is a markup language: it describes what data are, and not how to manipulate those data. On the other hand, programming languages make it possible to mainpulate data. In effect, JavaScript was intended to extend HTML to make it more interactive.

What can you do with JavaScript? A great many things:

Because of JavaScript's great power, it is now being used as a core component of dynamic HTML, a ``hot new web technology'' of the instant (unless that instant has already passed).

About JavaScript

The folks at Netscape tried to make JavaScript usable by novices, but also familiar to ``real programmers''. Hence, it started as a small language (for novices), but it looks a lot like the programming language C (for programmers). JavaScript is not designed for large programs, and does not always do well with such. However, it does suffice for many small and medium-sized tasks.

JavaScript takes ideas from both the imperative and object-oriented paradigms. In particular, it supports traditional imperative components, such as

However, JavaScript adds ``objects'' to the mix. In a sense, objects are groups of data and related functions (sometimes called ``methods''). Objects are similar to records in many imperative languages, although they are much more powerful. JavaScript also adds events and event handlers. In effect, you can write programs that say ``when this happens, do this''. However, you are limited in the events you can respond to. (There are many more objects in JavaScript 1.2; we won't discuss them.)

Client-Side vs. Server-Side Programming

JavaScript is primarily used as a client-side language, in that JavaScript programs are part of HTML pages, with the JavaScript code being exectued by the browser. However, Netscape also allows the use of JavaScript for writing CGI scripts in their LiveWire server, permitting server-side JavaSript. We will consider only client-side issues.

A History of JavaScript

Netscape introduced JavaScript with version 2.0 of their Navigator browser. That was JavaScript 1.0. As people began to develop programs and found deficiencies, Netscape extended and improved the language for version 3.0 of their Navigator browser, leading to JavaScript 1.1. With the release of Netscape Communicator (Navigator 4.0), JavaScript was extended to version 1.2

Because so many pages began to incorporate JavaScript scripts, Microsoft felt compelled to include support JavaScript in version 3.0 of their Internet Explorer browser. They call their version of JavaScript, JScript.

Unfortunately, the three versions of JavaScript differ somewhat in the commands and objects they support. In this tutorial, I'll be primarily covering topics from 1.1, the version supported by Navigator 3.0 (and mostly by 4.0).

Alternate Languages

JavaScript is not the only way to make pages interactive, although it is one of the most convenient. Alternatives include CGI, Java, VBScript, and some advanced features of HTML.

Before the proliferation of web languages, the primary mechanism for building interactive pages was CGI, the common gateway interface. With CGI, HTML pages can send information to programs that reside on servers, and the servers can generate new pages based on that information. CGI script are ideal for search engines and other applications in which data reside on the server. However, pages using CGI scripts are not fully interactive; in effect, the user simply visits a sequence of pages that remain static within the viewer. JavaScript, because it runs on the user's computer, allows much more dynamic pages. On the other hand, it cannot easily obtain information from a server.

Sun Microsystems developed Java as an ``industrial strength'' language for program development. They soon realized that it was also appropriate for including programs within web pages. However, Java programs are generally independent of the surrounding page: they cannot manipulate the page, and the page cannot manipulate the Java programs. (A combination of Java and JavaScript now permits some page/application communication.)

VBScript is Microsoft's alternative to JavaScript. It is somewhat more readable than JavaScript, and builds on an installed base of Visual Basic users and programmers. However, it is supported only by Internet Explorer. There have also been questions raised as to the security of using VBScript.

Until the development of those languages, some of the ``features'' of a programming language needed to be supported by HTML (or variants thereof) and the browser. For example, there are tags in HTML to load another page after some time progresses, or to test for browser support of some tags. For example, there is a <noframes> tag for browsers that don't support frames.

Because JavaScript is supported by both major browsers, it is the choice for many applications. Because Navigator and Communicator are now free (as, admittedly, is Internet Explorer), they make an appropriate platform.

Getting Started with JavaScript

Introduction

JavaScript is a programming language for making interactive web pages. Java looks a lot like C (a popular programmming language) and supports standard programming concepts like variables, conditionals, loops, functions, and objects.

Events

JavaScript is an event-based language. Most (but not all) JavaScript programs work under the model "when this happens, do something". What are some common events?

How do you tell JavaScript (or, more precisely, your browser) to react to your event? You add an

eventHandler="whatToDo"

parameter to the appropriate tag (body tag, a tag, input tag, etc.)

For now, many of our examples will be based on buttons and the onClick event and will have the form

<form name="sample">
<input type="button" name="clickme" value="Click Me"
       onClick="...">
</form>

As you may have observed from this short template, it's helpful (and almost necessary) if you name your forms.

Input and Output

Since we'll need some commands to get started, we'll begin with input and output. For now, we'll simply describe the commands. In the next section, we'll see how to incorporate them into a page.

One way to provide information to the reader is with the alert(text) function. This function brings up an alert box which displays the argument to the function. Many people find the alert box a simple way of providing a greeting without "muddying" the underlying HTML.

A sample program

A similar way to obtain information from the reader is with the prompt(request,default) function. This function brings up a dialog box in which the reader can type a response. In most cases, you will want to include a default setting. The function returns the string the reader entered.

A sample program

You can also put information into fields in a form with

document.formname.fieldname.value = ...

You'll need to fill in the name of the form and the name of the field (which is why they're in italics).

A sample program

Finally, you can set the information on the status bar of the window with

window.status="..."

This allows you to give some information to the reader without forcing him or her to respond to a dialog box. At the same time, you make sure that the information is some place that the reader will see it.

A sample program

JavaScript Programs

Although you will generally incorporate JavaScript in HTML pages, you can also save them as xxx.js files and load them into navigator. This is often useful for quick testing of concepts.

However, there are many advantages to embedding your JavaScript in HTML code. Among others, you can load JavaScript libraries within HTML pages, but not within other JavaScript files.

Putting JavaScript in HTML Files

Their are a number of ways to insert JavaScript code into HTML documents. We will begin with two of the simpler ones.

For JavaScript code that is to be executed directly, one uses the <SCRIPT> tag. The tag has two optional parameters,

For example, a simple JavaScript program might include

<script language="javascript">
alert("Welcome to my page.");
</script>

The src parameter is particularly useful, as it lets you reuse your JavaScript code. I strongly encourage you to develop general functions, and then incorporate them into your program using the <script src="..."> tag.

We can extend that simple JavaScript program to incorporate a library file as follows. Note that we need two sets of <SCRIPT> tags: one set to load the library and another to call a function from that library.

<script language="javascript" src="greet.js">
</script>
<script language="javascript">
greet("Sam");
</script>

Objects and Methods

JavaScript is at least somewhat object-based. That is, it presents many things to you as objects, and lets you manipulate them as such. For example, you can refer to the current window as window or the current document as document.

The pieces of information associated with an object are called the properties of that object. A property may be a number, some text, or even another object). To refer to a property of an object, you use the name of the object, a period, and the name of the propety. For example, you can obtain the title of a document as document.title.

Objects also have associated functions, which are normally called methods. These are the things that the object knows how to do. For example, you could tell the document to close itself with document.close().

For certain types of predefined objects, such as windows and arrays, you create a new object using the new command.

Variables

As with many programming languages, JavaScript allows you to define and use variables -- named containers of information. Unlike many languages, JavaScript supports only untyped variables. You can use the same variable to store some text, a number, or an object.

You assign values to variables by writing the variable name, an equals sign, and the expression you want to assign to the variable. For example, alpha=2 assigns the value 2 to the variable alpha.

You declare a new variable with var varname If the declaration is within a function, the variable is local to that function. If the declaration is outside of a function, the variable is global (accessible from any function).

Surprisingly, JavaScript does not require you to declare variables. However, I strongly encourage you to declare your variables and add a note as to how you're using them.

Comments

As you develop longer and longer programs, you should insert notes to yourself (or to others) to help explain the program. These are typically called comments. In JavaScript, comments begin with two slashes, //, and end at the end of a line.

Expressions

JavaScript permits normal mathematical expressions, such as 2*10+3. It also permits you to use variables within expressions.

JavaScript also provides some basic string operations. In particular, + is used to concatenate strings. If you happened to have the user's name stored in the variable userName, you could create a greeting with

var greeting // A greeting to the user
greeting = "Hello " + userName + ".  Welcome to this page."

Inserting Text and HTML

Up to this point, we've only been interacting with the user by putting up dialogue boxes or inserting information in fields. Clearly, we'd like to do more. For example, we might want to insert text or HTML into a document. JavaScript allows us to do this with the write method of the document object. That is, you use document.write(text) to insert text. The text is inserted at the point that the JavaScript code is executed. You use document.writeln(text) to write the text an add a carriage return to the end of the line.

For example, we might create a page that greets a user by name with

<script language="javascript">
var userName
userName = prompt("Please enter your name", "")
document.write("

Hello " + userName + " welcome to my page.

") </script>

Note that I've included spaces in the strings so that the user's name does not run into the surrounding text. Also note that I've included HTML tags within the text I've written.

There is a drawback to the document.write() method: it only works when the document is loaded (or reloaded). Hence, you cannot later insert text into your document (unless you reload it).

You can play with a sample page that includes this function.


History

Saturday, 22 January 2000

Monday, 28 February 2000

Back to Computer Viruses. On to Lab: Introduction to JavaScript.


Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.

This page may be found at http://www.math.grin.edu/~rebelsky/Courses/CS105/2000S/Outlines/outline.21.html

Source text last modified Mon Feb 28 09:48:45 2000.

This page generated on Mon Feb 28 09:45:12 2000 by Siteweaver. Validate this page's HTML.

Contact our webmaster at rebelsky@grinnell.edu