Web Programming II
Web Programming II
Client-side scripting
• client-side script: code runs in browser after page is sent back from server
• often this code manipulates the page or responds to user actions
What is JavaScript?
• a lightweight programming language ("scripting language")
• used to make web pages interactive
• insert dynamic text into HTML (ex: user name)
• react to events (ex: page load user click)
• get information about a user's computer (ex: browser type)
• perform calculations on user's computer (ex: form validation)
• a web standard (but not supported identically by all browsers)
• NOT related to Java other than by name and some syntactic similarities
+ = JavaScript
• interpreted, not compiled
• more relaxed syntax and rules
• fewer and "looser" data types
• variables don't need to be declared
• errors often silent (few exceptions)
• key construct is the function rather than the class
• "first-class" functions are used in many situations
• contained within a web page and integrates with its HTML/CSS content
• integers and real numbers are the same type (no int vs. double)
• same operators: + - * / % ++ -- = += -= *= /= %=
• similar precedence to Java
• many operators auto-convert types: "2" * 3 is 6
String type
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant'; // can use "" or ' '
/* multi-line comment */
• identical to Java's comment syntax
• recall: 4 comment syntaxes
• HTML: <!-- comment -->
• CSS/JS/PHP: /* comment */
• Java/JS/PHP: // comment
• PHP: # comment
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1[i] + s1[i];
}
// s2 stores "hheelllloo"
Math object
var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);
• methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin, sqrt,
tan
• properties: E, PI
Logical operators
• Relational: > < >= <=
• Logical: && || !
• Equality: == != === !==
• most logical operators automatically convert types. These are all true:
• 5 < "7"
• 42 == 42.0
• "5.0" == 5
• The === and !== are strict equality tests; checks both type and value:
• "5.0" === 5 is false
Boolean type
var iLikeJS = true;
var ieIsGood = "IE6" > 0; // false
if ("web dev is great") { /* true */ }
if (0) { /* false */ }
do {
statements;
} while (condition);
Popup boxes
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
Arrays
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
Array methods
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
• join merges an array into a single string, placing a delimiter between them
Defining functions
function name() {
statement ;
statement ;
...
statement ;
}
function myFunction() {
alert("Hello!");
alert("How are you?");
}
• the above could be the contents of example.js linked to our HTML page
• statements placed into functions can be evaluated in response to user events
Event-driven programming
Buttons: <button>
the canonical clickable UI control (inline)
<button>Click me!</button>
JavaScript functions
function name() {
statement ;
statement ;
...
statement ;
}
function myFunction() {
alert("Hello!");
alert("How are you?");
}
• the above could be the contents of example.js linked to our HTML page
• statements placed into functions can be evaluated in response to user events
Event handlers
<element attributes onclick="function();">...
Accessing elements:
document.getElementById
var name = document.getElementById("id");
function changeText() {
var textbox = document.getElementById("output");
textbox.value = "Hello, world!";
}
function swapText() {
var span = document.getElementById("output2");
var textBox = document.getElementById("textbox2");
var temp = span.innerHTML;
span.innerHTML = textBox.value;
textBox.value = temp;
}
Freshman? Freshman?
Property Description Example
value the text in an input control $("sid").value could be "1234567"
checked whether a box is checked $("frosh").checked is true
disabled whether a control is disabled (boolean) $("frosh").disabled is false
readOnly whether a text box is read-only $("sid").readOnly is false
Modifying text inside an element
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "Welcome to our site!"; // change text on page
Abuse of innerHTML
// bad style!
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "<p>text and <a href="page.html">link</a>";
window.onload = function() {
document.getElementById("clickme").onclick = changeColor;
};
function changeColor() {
var clickMe = document.getElementById("clickme");
clickMe.style.color = "red";
}
Property Description
style lets you set any CSS style property for an element
• contains same properties as in CSS, but with camelCasedNames
• examples: backgroundColor, borderLeftWidth, fontFamily
• style properties must be set as strings, often with units at the end
clickMe.style.width = 200;
clickMe.style.width = "200px";
clickMe.style.padding = "0.5em";
• write exactly the value you would have written in the CSS, but in quotes
• every function contains an array named arguments representing the parameters passed
• can loop over them, print/alert them, etc.
• allows you to write functions that accept varying numbers of parameters
• loops over every index of the array, or every property name of the object
• using this is actually discouraged, for reasons we'll see later
Arrays as maps
var map = [];
map[42] = "the answer";
map[3.14] = "pi";
map["champ"] = "suns";
• methods
• getDate, getDay, getMonth, getFullYear, getHours, getMinutes,
getSeconds, getMilliseconds, getTime, getTimezoneOffset, parse,
setDate, setMonth, setFullYear, setHours, setMinutes, setSeconds,
setMilliseconds, setTime, toString
• quirks
• getYear returns a 2-digit year; use getFullYear instead
• getDay returns day of week from 0 (Sun) through 6 (Sat)
• getDate returns day of month from 1 to (# of days in month)
• Date stores month from 0-11 (not from 1-12)
var pt = {
x: 4,
y: 3
};
alert(pt.x + ", " + pt.y);
var pt = {
x: 4, y: 3,
distanceFromOrigin: function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
};
alert(pt.distanceFromOrigin()); // 5
• the above code is ugly and doesn't match the new syntax we're used to
Constructor functions
// Constructs and returns a new Point object.
function Point(xValue, yValue) {
this.x = xValue;
this.y = yValue;
this.distanceFromOrigin = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
}
Modifying a prototype
// adding a method to the prototype
className.prototype.methodName = function(parameters) {
statements;
}
Point.prototype.distanceFromOrigin = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
• adding a method/field to a prototype will give it to all objects using that prototype
• better than manually adding each method to each object (copying the method N times)
• we generally put only methods and constant data (not fields!) in a prototype object
• what would happen if we put the x and y fields in Point.prototype?
• Exercise: Add distance and toString methods.
• to make a "subclass", tell its constructor to use a "superclass" object as its prototype
• why not just write it this way?
SubClassName.prototype = SuperClassName.prototype; // connect them
Pseudo-inheritance example
// Constructor for Point3D "class"
function Point3D(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
};