Navigation


Lesson: Introducing JavaScript

Goals

Illustrate what JS is used for. Show how JS code is included in pages. Introduce variables. Show simple I/O with prompt() and alert(). Introduce the if statement. Introduce functions.

Notes

JS adds interactivity to Web pages. When the user types something (like when s/he fills in a form) or clicks something (like a menu entry or a button), you can run JS code. That code might check what the user types to make sure it doesn't have errors, jump to a new page, or whatever.

Here are some samples that show you what JS can do.

Circumference 1

This page computes the circumference of a circle. Try it now.

Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Circumference</title>
        <script type="text/javascript">
            diameter = prompt("Diameter?");     1 
            circum = diameter * 3.14159;      2 
            alert("Circumference of circle with a diameter of " + diameter
                + " is " + circum);     3  
        </script>
    </head>
    <body>
    </body>
</html>

The JS is in <script> tags. It's run when the browser loads the page.

At 1, the prompt function shows a dialog box. It waits until the user types something. Whatever the user types is stored in a variable called diameter. A variable is a piece of memory with a name. When the program refers to that variable later, the data will be pulled from memory and used.

Variables can contain two types of data: numbers, and strings. A string is a text value, like "life is hard, and then you die". But in this program, we are just dealing with numbers.

I could use variable names like xthing, or w4SkkfJKJL34_die_wilkins_die, instead of diameter. While such variable can be emotionally satisfying, they make your code harder to read. Use meaningful variables names. You are being watched.

At 2, there is a computation. The value stored in diameter is pulled from memory, and multiplied by 3.14159. 3.14159 is a constant, a fixed value. The result is put into the variable circum.

BTW, variables names are case sensitive. So Pig and pig and pIG are all different variables. If I had typed Diameter instead of diameter in 2, the program wouldn't work.

At 3, a message is shown to the user. There's some text, the value of diameter, some more text, and then the value of circum.

Exercise 1. Circle area

Change the code so that it computes the area of a circle from the diameter. The formula is:

area = (diameter/2) * (diameter/2) * 3.14159

The prompt at 1 will stay the same. Change the formula at 2 to compute the area. Change the output at 3.

Do not read more until you try it.

Did you do it? Huh? HUH?!

Do it, or I will kill this poor creature.

Mouse

Isn't it cute? And it will die, all because of you!

Unless you do the exercise.

Solution - do it yourself first!

Circumference 2

This page also computes the circumference of a circle. Try it now.

Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
                    "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Circumference</title>
        <script type="text/javascript">
            function circum(){     1 
                diameter = prompt("Diameter?");
                cir = diameter * 3.14159;
                alert("Circumference of circle with a diameter of " + diameter +
                    " is " + cir);
            }
        </script>
    </head>
    <body>
        <h1>Circumference</h1>
        <p><button type="button" onclick="circum()">Compute</button></p>     2 
    </body>
</html>

At 1, a function is declared. A function is a set of JS statements that is given a name. When a function is called, all of the statements in it are executed. Functions are very important in programming.

Functions are not executed automatically when the browser loads them. They are just remembered.

A button is created at 2. When it is clicked, the circum() function is run. "Click" is an event. It's something that can happen to the button. onClick() ties (or "binds") the button to the event.

The parentheses are part of the function's name. cir is a variable. circum() is a function.

Exercise 2. Circle area walks again

Change the code so that it computes the area of a circle from the diameter. Change the name of the function at 2, and make any other changes you need.

Do it now, or I will send this thing after you:

Thing

Look at its crazy eyes. You can tell it's higher than a kite.

Solution - do it yourself first!

Circumference 3

This page also computes the circumference of a circle. Try it now.

Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
                "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Circumference</title>
        <script type="text/javascript" src="jquery-1.3.1.min.js"></script>      3  
        <script type="text/javascript">
            function compute_circum() {
                diameter = $('#diameter').val();      4  
                circum = diameter * 3.14159;
                $('#circumference').html(circum);      5  
            }
        </script>
    </head>
    <body>
        <h1>Circumference</h1>
        <div>
            <label for="diameter">Diameter</label><br>
            <input type="text" id="diameter"><br>      1  
            <button type="button" onclick="compute_circum()">Compute</button>      2  
        </div>
        <p>Circumference: <span id="circumference"></span></p>      6  
    </body>
</html>

There is a text field at 1. It has an id of diameter. JS code can use the id to refer to it.

The button at 2 runs a function.

The code at loads 3 the way cool jQuery library. It makes messing with document contents easier.

The code at 4 gets the contents of the field diameter and stores it in a variable.

The code at 5 sets the HTML contents of the span with the id of circumference (see 6).

Exercise 3. Revenge of circle area

Change the code so that it computes the area of a circle from the diameter.

Ok, this time, if you don't do it, er... You won't know how to write JS, will fail in the workplace, get fired, your boyfriend/girlfriend/spouse will leave you, and you will ride the rails for the rest of your life. Until you are shanked in a dispute over the last piece of road kill. The other hobos will pull out your intestines and grill them, as you slowly bleed to death. Your only comfort will be that your intestines smell pretty good when grilled.

And you will have it coming, because you skipped the exercise.

Solution - do it yourself first!

Circumference 4

This page also computes the circumference of a circle. Try it now.

Here is the code for the function. The rest of it hasn't changed.

function compute_circum() {
    //Erase the current answer.      1  
    $('#circumference').html('');      2  
    //Get the user's input.
    diameter = $('#diameter').val();
    //Anything there?
    if ( diameter == '' ) {      3  
        alert('Please enter a diameter.');
        return;      4  
    }
    //Did the user enter a valid number?
    if ( isNaN(diameter) ) {      5  
        alert('Please enter a valid number.');
        return;
    }
    //Did the user enter a positive number?
    if ( diameter <= 0 ) {      6  
        alert('Please enter a positive number.');
        return;
    }
    //All OK. Do the computations. 
    circum = diameter * 3.14159;
    //Show the output.
    $('#circumference').html(circum);
}

1 is comment. Any line starting with // is ignored by the browser. Comments are VITs (very important things). Like your eyes. Comments tell people who read your code what you were thinking when you wrote it. Comments make it easier to change your code. With comments, changes are faster, and more accurate. Therefore cheaper. And all things good. Comments are like puppies, and cupcakes. Yum! The cupcakes, not the puppies. You sicko.

2 erases the last answer the user got. So s/he doesn't get confused, the poor dear.

3 is an if statement. It tests whether the user entered anything in the diameter field before clicking the button. An if statement has a test in it that's either true or false. If it's true, then the statements in the braces will be executed. If it's false, the browser will skip the statements in the braces.

== is true when the thing on the left and the thing on the right are equal to each other. So (2 == (3-1)) is true. ('cat' == 'dog') is false. ('Dog' == 'dog') is false. ('d'+'og' == 'dog') is true.

So, ( diameter == '' ) is true if diameter is empty. '' does not have a space between it. It's a quote followed immediately by another quote. If diameter is empty, the user forgot to type anything in the input field. What to do? The program shows an error message, and at 4 executes the return statement. return immediately leaves the function it is in. So compute_circum() stops at once. But this only happens if diameter is empty.

But even if diameter is not empty, it might not have a number in it. Maybe the user typed "bonobo, the party primate." Maybe the user is insane. Maybe the user is eating his/her own grilled intestines, which tends to create some tasty confusion.

The if statement at 5 uses the isNaN() function. It's a built-in function, part of JS. It takes one parameter in the parentheses (parameters are also called arguments). isNaN() will return true if the parameter is not a number. isNaN means "is not a number."

So, isNaN("I like big, er, budgets, yeah, that's it, budgets") is true, because the parameter is not a number. isNaN('34') is false, because the parameter is a number. isNaN('-3321.3434') is false as well.

Another problem is that the user might have entered a diameter of zero or less. That's what 6 checks for.

There's more to know about the if statement. Check the links below.

Exercise 4. The end of circle area

Change the code so that it computes the area of a circle from the diameter.

Don't want to do it? Do you know what happened to Sir Robin?

Solution - do it yourself first!

Patterns

A pattern is a common way of doing something. When you write a program, rather than starting from scratch, think about similar things you've done in the past, or things you've seen other programmers do. Then copy what works.

The circumference 4 program shows some common patterns in Web programming. There is a form with fields on it:

  • Input form pattern: the user fills in form fields, and clicks a button. This triggers the button's click event. The click event calls a function to process the data.

So, if you need to get some input from a user, you know how to do it. Set up a form with input fields and a button, create a function, and make the button call the function. You know this will work, because you've used the pattern before. In fact, you can copy-and-paste directly from the circumference 4 program.

Note that the input form pattern is not the only way to do things. The first version of the circumference program used the prompt() function.

Here's another pattern:

  • Process form input pattern:
    • Get the user's data from the form.
    • Validate the data. If there's a problem, show an error message, and stop processing.
    • Process the data.
    • Show the results on the page.

You know this works, because you've seen it work. The code in the circumference 4 program gets the user data, checks it with if statements, and so on. If you want to know how to do each step in the pattern, just look at the circumference 4 program for an example. Copy what you need.

The more programs you write, the more patterns you'll know, and the easier it will be to write new programs.

 

This page has been brought to you by the letter D, for death, doom, and despair. You can't spell depression without D.

Exercises

Exercise - Invert a number
Exercise - The name game

Links

Here are some more JavaScript resources. But there's something you should know. There are lots of ways to write JS. We'll just be looking at a tiny part of what can be done with the language. Further, we'll be using jQuery to smooth over a lot of the rough edges of JS programming. This makes it easier for you to learn about JS, but it means that most of the JS resources on the Web use JS constructs that we won't be covering.

The following have been carefully selected for your enjoyment, without unpleasant side effects like ulna itch, tongue sweat, and crepuscular swelling. Enjoy.