Javascript

CSE 190 M (Web Programming) Spring 2007

University of Washington

Reading: Sebesta Ch. 4 sections 4.1 - 4.6.4, 4.8, 4.9.1 - 4.9.3, 4.14

Except where otherwise noted, the contents of this presentation are © Copyright 2007 Marty Stepp and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.0 Strict Valid CSS!

What is Javascript?

Differences between Javascript and Java

Java + marijuana = Javascript

Injecting Dynamic Text: document.write()

document.write("message");

Variables

var name = value;
var clientName = "Connie Client";
var age = 32;
var weight = 137.4;

Javascript keywords

abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with

Operators

for loop

for (initialization; condition; update) {
    statements;
}
for (var i = 0; i < 10; i++) {
    document.write("<p>" + i + " squared = " + 
                   (i * i) + "</p>");
}

Inserting Javascript in HTML

Javascript in HTML body (example)

<body>
    ...
    <script type="text/javascript">
    Javascript code
    </script> 
    ...
</body>

Practice problem: Hello World!

  1. Write a page that displays "Hello World!" using Javascript.
  2. Make "Hello World!" appear 1000 times.
  3. Make it so there's only one "Hello World!" per line.

Javascript in HTML head (example)

<head>
    ...
    <script type="text/javascript">
    Javascript code
    </script> 
    ...
</head>

Linking to a Javascript file (example)

<script src="filename" type="text/javascript"></script>
<script src="example.js" type="text/javascript"></script>

String type

var clientName = "Connie Client";

More about String

Number type

var enrollment = 99;
var median142Grade = 2.8;

if/else statement

if (condition) {
    statements;
} else if (condition) {
    statements;
} else {
    statements;
}

Boolean type

var iLike190M = true;

while loop

while (condition) {
    statements;
}
do {
    statements;
} while (condition);

Math object

var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);

Comments

// single-line comment

/*
multi-line comment
*/

Practice problem: Random image

A "Person of the Day" page has been made for this class. Today's winner is Marty, but you have two favorite pictures of him!

Randomly choose between these two pictures on each page refresh.

Functions

function name(parameterName, ..., parameterName) {
    statements;
}
function quadratic(a, b, c) {
    return -b + Math.sqrt(b*b - 4*a*c) / (2*a);
}

Calling functions

name(parameterValue, ..., parameterValue);
var root = quadratic(1, -3, 2);

Global and local variables

var count = 1;

function f1() { 
    var x = 999;
    count *= 10;
}
function f2() { count++; }

f2();
f1();

Popup boxes

alert("message");     // message
confirm("message");   // returns true or false
prompt("message");    // returns user input string

alert confirm prompt

Date object

var today = new Date();               // today
var midterm = new Date(2007, 4, 4);   // May 4, 2007

Event handlers

<h2 onclick="myFunction();">Click me!</h2>

Click me!


Practice problem: Birthdays

  1. Modify the "Person of the Day" page so that the number of days until Marty's birthday are displayed in an alert box when his picture is clicked.
  2. When the previous people of the day's names are clicked the number of days until their birthday should be displayed.

Firefox Web Developer extension

View Generated Source

Arrays

var stooges = new Array();
stooges[0] = "Larry";
stooges[1] = "Moe";
stooges[2] = "Curly";
var stooges = new Array("Larry", "Moe", "Curly");
var stooges = ["Larry", "Moe", "Curly"];

Array methods

Arrays as lists

var a = new Array();
a.push("Morgan");          // Brian
a.push("Brian");           // Morgan,Brian
a.unshift("Kenneth");      // Kenneth,Morgan,Brian
a.push("Helene", "Jeff");  // Kenneth,Morgan,Brian,Helene,Jeff
a.shift();                 // Morgan,Brian,Helene,Jeff
a.pop();                   // Morgan,Brian,Helene
a.sort();                  // Brian,Helene,Morgan

Strings and arrays: split and join

var s = "the quick brown fox";
var a = s.split(" ");          // [the,quick,brown,fox]
a.reverse();                   // [fox,brown,quick,the]
s = a.join("!");               // "fox!brown!quick!the"

Special values: undefined and null

var ned;
var benson = 9;

// at this point in the code,
//   ned is null
//   benson is 9
//   caroline is undefined

The typeof function

typeof(value)

Timers: setTimeout, clearTimeout

function delayedMessage() {
    var myTimer = setTimeout("alert('Booyah!');", 5000);
}
<h2 onclick="delayedMessage();">Click me now!</h2>

Click me now!


setInterval, clearInterval

function repeatedMessage() {
    var myTimer = setInterval("alert('Rudy!');", 1000);
}
<h2 onclick="repeatedMessage();">Click me now!</h2>

Click me now!


Common bug: local variable in timer

function delayed(text) {
    var myTimer = setTimeout("alert(text);", 1000);
}
<h2 onclick="delayed('hello');">Click me now!</h2>

Click me now!


Practice problem: Stop the timer

----- More Arrays and Objects -----

More Arrays and Objects

The arguments array

function example() {
    for (var i = 0; i < arguments.length; i++) {
        alert(arguments[i]);
    }
}
example("how", "are", "you");

Arrays as maps

var map = new Array();
map[42] = "the answer";
map[3.14] = "pi";
map["champ"] = "suns";

Array map example

...

The "for each" loop

for (var name in arrayOrObject) {
    do something with arrayOrObject[name];
}