Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica Miller.
verb(noun)
), more object-oriented (noun.verb()
)PHP already allows us to create dynamic web pages. Why also use a client-side language like JavaScript?
main
method and run sequentially<button>
the most common clickable UI control (inline)
<button>Click me!</button>
script
<script src="filename" type="text/javascript"></script>
<script src="example.js" type="text/javascript"></script>
script
tag should be placed in HTML page's head
.js
filebody
or head
(like CSS)
alert
alert("message");
alert("IE6 detected. Suck-mode enabled.");
function name() { statement ; statement ; ... statement ; }
function myFunction() { alert("Hello!"); alert("How are you?"); }
example.js
linked to our HTML page<element attributes onclick="function();">...
<button onclick="myFunction();">Click me!</button>
onclick
is just one of many event HTML attributes we'll usea set of JavaScript objects that represent each element on the page
div
getElementById
var name = document.getElementById("id");
<button onclick="myFunction2();">Click me!</button> <span id="output">replace me</span>
function myFunction2() { var span = document.getElementById("output"); span.innerHTML = "Hello, how are you?"; }
document.getElementById
returns DOM object for an element with a given id
innerHTML
property
var name = expression;
var clientName = "Connie Client"; var age = 32; var weight = 127.4;
var
keyword (case sensitive)Number
, Boolean
, String
, Array
, Object
, Function
, Null
, Undefined
typeof
Number
type
(7.2.2)
var enrollment = 99; var medianGrade = 2.8; var credits = 5 + 4 + (2 * 3);
int
vs. double
)+ - * / % ++ -- = += -= *= /= %=
"2" * 3
is 6
// single-line comment
/* multi-line comment */
<!-- comment -->
/* comment */
// comment
# comment
<div id="main" class="foo bar"> <p>Hello, <em>very</em> happy to see you!</p> <img id="icon" src="images/borat.jpg" alt="Borat" /> </div>
var div = document.getElementById("main"); var image = document.getElementById("icon");
tagName
: element's HTML tag, capitalized;
div.tagName
is "DIV"
className
: CSS classes of element;
div.className
is "foo bar"
innerHTML
: HTML content inside element;
div.innerHTML
is "\n <p>Hello, <em>very</em> happy to ...
src
: URL target of an image;
image.src
is "images/borat.jpg"
<input id="studentid" type="text" size="7" maxlength="7" /> <input id="freshman" type="checkbox" checked="checked" /> Freshman?
var sid = document.getElementById("studentid"); var frosh = document.getElementById("freshman");
value
: the text in an input control
sid.value
could be "1234567"
checked
, disabled
, readOnly
: whether a control is selected/disabled/etc.
frosh.checked
is true
My program does nothing.(most errors produce no output)
It just prints undefined
.
(many typos lead to undefined variables)I get an error that says, foo
has no properties.
alert
at the top of it and make sure it appears.
Since Javascript has no compiler, many errors will cause your Javascript program to just "do nothing." Some questions you should ask when this happens:
alert
at the VERY TOP of your script: alert
at the start of the appropriate function: "hello"
or "here"
Object foo has no properties
ReferenceError: foo is not defined
TypeError: foo.bar is not a function
id
function foo() {
... // missing closing curly brace!
function bar() {
...
}
String
type
(7.2.7)
var s = "Connie Client"; var fName = s.substring(0, s.indexOf(" ")); // "Connie" var len = s.length; // 13 var s2 = 'Melvin Merchant';
charAt
,
charCodeAt
,
fromCharCode
,
indexOf
,
lastIndexOf
,
replace
,
split
,
substring
,
toLowerCase
,
toUpperCase
charAt
returns a one-letter String
(there is no char
type)length
property (not a method as in Java)""
or ''
+
:
1
+ 1 is 2
, but
"1"
+ 1 is "11"
String
\' \" \& \n \t \\
String
s:
var s1 = String(myNum); var s2 = count + " bananas, ah ah ah!"; var n1 = parseInt("42 is the answer"); // 42 var n2 = parseFloat("booyah"); // NaN
String
:
var firstLetter = s[0]; // doesn't work in IE
var lastLetter = s.charAt(s.length - 1);
for
loop
(same as Java)
(7.2.8)
for (initialization; condition; update) { statements; }
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.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
var rand1to10 = Math.floor(Math.random() * 10 + 1); var three = Math.floor(Math.PI);
null
and undefined
(7.2.10)
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
undefined
: has not been declared, does not existnull
: exists, but was specifically assigned a null
value> < >= <= && || ! == != === !==
5 < "7"
is true
42 == 42.0
is true
"5.0" == 5
is true
===
and !==
are strict equality tests; checks both type and value
"5.0" === 5
is false
if/else
statement
(same as Java)
(7.3.2)
if (condition) { statements; } else if (condition) { statements; } else { statements; }
if/else
statementvar iLike190M = true; var ieIsGood = "IE6" > 0; // false if ("web dev is great") { /* true */ } if (0) { /* false */ }
Boolean
0
, 0.0
, NaN
, ""
, null
, and undefined
Boolean
explicitly:
var boolValue = Boolean(otherValue);
var boolValue = !!(otherValue);
while
loops
(same as Java)
(7.3.5)
while (condition) { statements; }
do { statements; } while (condition);
break
and continue
keywords also behave as in Java
// global code; like "main"
var count = 1;
f2();
f1();
function f1() {
var x = 999;
count = count * 10;
}
function f2() { count++; }
count
above is global (can be seen by all functions)x
above is local (can be seen by only f1
)f1
and f2
can use and modify count
(what is its value?)function name(parameterName, ..., parameterName) { statements; return expression; }
function quadratic(a, b, c) { return -b + Math.sqrt(b * b - 4 * a * c) / (2 * a); }
var
is not written on parameter declarationsreturn
statement return undefined
name(parameterValue, ..., parameterValue);
var root = quadratic(1, -3, 2);
undefined
valuefunction foo() { Bar(); // capitalized wrong ... function bar() { ... }
undefined
is usedundefined
as an event handler, nothing happens (fails silently)undefined
var name = []; // empty array var name = [value, value, ..., value]; // pre-filled name[index] = value; // store element
var ducks = ["Huey", "Dewey", "Louie"]; var stooges = []; // stooges.length is 0 stooges[0] = "Larry"; // stooges.length is 1 stooges[1] = "Moe"; // stooges.length is 2 stooges[4] = "Curly"; // stooges.length is 5 stooges[4] = "Shemp"; // stooges.length is 5
length
property (grows as needed when elements are added)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
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"
split
breaks apart a string into an array using a delimiter
join
merges an array into a single string, placing a delimiter between themalert("message"); // message confirm("message"); // returns true or false prompt("message"); // returns user input string
body
(example)
<script type="text/javascript">
JavaScript code
</script>
head
or body
typeof
functiontypeof(value)
function foo() { alert("Hello"); }
var a = ["Huey", "Dewey", "Louie"];
true
:
typeof(3.14) === "number"
typeof("hello") === "string"
typeof(true) === "boolean"
typeof(foo) === "function"
typeof(a) === "object"
typeof(null) === "object"
typeof(undefined) === "undefined"
arguments
array
function example() {
for (var i = 0; i < arguments.length; i++) {
alert(arguments[i]);
}
}
example("how", "are", "you"); // alerts 3 times
arguments
representing the parameters passedfor (var name in arrayOrObject) { do something with arrayOrObject[name]; }
var map = []; map[42] = "the answer"; map[3.14] = "pi"; map["champ"] = "suns";
Map
collection or PHP's associative arraysvar today = new Date(); // today var midterm = new Date(2007, 4, 4); // May 4, 2007
getYear
returns a 2-digit year; use getFullYear
insteadgetDay
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)document.write
document.write("message");
body
document.write
eval
(evil?) functioneval("JavaScript code");
eval("var x = 7; x++; alert(x / 2);"); // alerts 4
eval
treats a String as JavaScript code and runs that code