Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, Victoria Kirst and Roy McElmurry IV. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.
PHP already allows us to create dynamic web pages. Why also use client-side scripting?
noun.verb()
, less procedural: verb(noun)
alert
alert("message");
alert("IE6 detected. Suck-mode enabled.");
var name = expression;
var age = 32; var weight = 127.4; var clientName = "Connie Client";
var
keyword (case sensitive)Number
, Boolean
, String
, Array
, Object
, Function
, Null
, Undefined
typeof
Number
type
var enrollment = 99; var medianGrade = 2.8; var credits = 5 + 4 + (2 * 3);
int
vs. double
)+ - * / % ++ -- = += -= *= /= %=
"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 ' '
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)+
: 1
+ 1 is 2
, but
"1"
+ 1 is "11"
String
\' \" \& \n \t \\
String
s:
var count = 10; var s1 = "" + count; // "10" var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah ah ah!" var n1 = parseInt("42 is the answer"); // 42 var n2 = parseFloat("booyah"); // NaN
String
, use [index] or charAt
:
var firstLetter = s[0]; var firstLetter = s.charAt(0); var lastLetter = s.charAt(s.length - 1);
// single-line comment
/* multi-line comment */
<!-- comment -->
/* comment */
// comment
# comment
for
loop
(same as Java)
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[i] + s1[i];
}
// s2 stores "hheelllloo"
var rand1to10 = Math.floor(Math.random() * 10 + 1); var three = Math.floor(Math.PI);
> < >= <= && || ! == != === !==
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)
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)
while (condition) { statements; }
do { statements; } while (condition);
break
and continue
keywords also behave as in Javavar 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
/
:
var a = s.split(/[ \t]+/);
join
merges an array into a single string, placing a delimiter between themfunction name() { statement ; statement ; ... statement ; }
function myFunction() { alert("Hello!"); alert("How are you?"); }
example.js
linked to our HTML pagenull
and undefined
var ned = null;
var benson = 9;
var caroline;
// 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 an empty or null
valuemain
; they respond to user actions called eventsscript
<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)
<button>
the canonical clickable UI control (inline)
<button>Click me!</button>
<element attributes onclick="function();">...
<button onclick="myFunction();">Click me!</button>
onclick
is just one of many event HTML attributes we'll usealert
window is disruptive and annoying
onclick
alerta set of JavaScript objects that represent each element on the page
div
objectName.attributeName
document.getElementById
var name = document.getElementById("id");
<button onclick="changeText();">Click me!</button> <input id="output" type="text" value="replace me" />
function changeText() { var textbox = document.getElementById("output"); textbox.value = "Hello, world!"; }
document.getElementById
returns the DOM object for an element with a given id
value
property
<button onclick="swapText();">Click me!</button> <span id="output2">Hello</span> <input id="textbox2" type="text" value="Goodbye" />
function swapText() { var span = document.getElementById("output2"); var textBox = document.getElementById("textbox2"); var temp = span.innerHTML; span.innerHTML = textBox.value; textBox.value = temp; }
innerHTML
property
this
<button onclick="okayClick();">OK</button>
// called when OK button is clicked
function okayClick() {
alert("booyah");
}
// where element is a DOM element object
element.onevent = function;
<button id="ok">OK</button>
var okButton = document.getElementById("ok"); okButton.onclick = okayClick;
<html> <head> <script src="myfile.js" type="text/javascript"></script> </head> <body> ... </body> </html>
// global code
var x = 3;
function f(n) { return n + 1; }
function g(n) { return n - 1; }
x = f(x);
script
tag
body
<html> <head> <script src="myfile.js" type="text/javascript"></script> </head> <body> <div><button id="ok">OK</button></div>
// global code document.getElementById("ok").onclick = okayClick; // error: null
head
is processed before page's body
has loaded
window.onload
event
// this will run once the page has finished loading function functionName() { element.event = functionName; element.event = functionName; ... } window.onload = functionName; // global code
window.onload
event that occurs at that momentwindow.onload
handler we attach all the other handlers to run when events occur
<button id="ok">OK</button> <!-- look Ma, no JavaScript! -->
// called when page loads; sets up event handlers function pageLoad() { document.getElementById("ok").onclick = okayClick; } function okayClick() { alert("booyah"); } window.onload = pageLoad; // global code
()
when attaching the handler
window.onload = pageLoad(); window.onload = pageLoad; okButton.onclick = okayClick(); okButton.onclick = okayClick;
window.onLoad= pageLoad; window.onload = pageLoad;
function(parameters) { statements; }
window.onload = function() { var okButton = document.getElementById("ok"); okButton.onclick = okayClick; }; function okayClick() { alert("booyah"); }
window.onload = function() { var okButton = document.getElementById("ok"); okButton.onclick = function() { alert("booyah"); }; };
element.style.color
.function okayClick() {this.style.color = "red";this.className = "highlighted"; }
.highlighted { color: red; }