Selected content adapted from material by Marty Stepp, Jessica Miller, and Victoria Kirst © 2012. Used by permission.
Server-side languages already allows us to create dynamic web pages. Why also use client-side scripting?
noun.verb()
, less procedural: verb(noun)
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
script
tag should be placed at the end of HTML content, just before closing </body>
tag.js
filebody
or head
(like CSS)
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
main
; they respond to user actions called events<button>
the canonical clickable UI control (inline)
<button>Click me!</button>
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 usealert
window is disruptive and annoying
a 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
// single-line comment
/* multi-line comment */
<!-- comment -->
/* comment */
// comment
# comment
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
:
var firstLetter = s[0]; // fails in IE var firstLetter = s.charAt(0); // does work in IE var lastLetter = s.charAt(s.length - 1);
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.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
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
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 and c#)
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 Javaalert("message"); // message confirm("message"); // returns true or false prompt("message"); // returns user input string
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 themobjectName.attributeName
<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>
Property | Description | Example |
---|---|---|
tagName
|
element's HTML tag |
document.getElementById("main").tagName is "DIV"
|
className
|
CSS classes of element |
document.getElementById("main").className is "foo bar"
|
innerHTML
|
content inside element |
document.getElementById("main").innerHTML is "\n <p>Hello, <em>ve...
|
src
|
URL target of an image |
document.getElementById("icon").src is "images/borat.jpg"
|
<input id="sid" type="text" size="7" maxlength="7" /> <input id="frosh" type="checkbox" checked="checked" /> Freshman?
Property | Description | Example |
---|---|---|
value
|
the text in an input control |
document.getElementById("sid").value could be "1234567"
|
checked
|
whether a box is checked |
document.getElementById("frosh").checked is true
|
disabled
|
whether a control is disabled (boolean) |
document.getElementById("frosh").disabled is false
|
readOnly
|
whether a text box is read-only |
document.getElementById("sid").readOnly is false
|
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "Welcome to our site!"; // change text on page
DOM element objects have the following properties:
innerHTML
: text and/or HTML tags inside a nodetextContent
: text (no HTML tags) inside a node
innerHTML
, but not supported in IE6
value
: the value inside a form controlinnerHTML
// bad style!
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "<p>text and <a href="page.html">link</a>";
innerHTML
can inject arbitrary HTML content into the pageinnerHTML
to inject HTML tags; inject plain text only
<button id="clickme">Color Me</button>
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 |
camelCasedNames
backgroundColor
, borderLeftWidth
, fontFamily
.style
when setting styles
var clickMe = document.getElementById("clickme");clickMe.color = "red";clickMe.style.color = "red";
likeThis
, not like-this
clickMe.style.font-size = "14pt";clickMe.style.fontSize = "14pt";
clickMe.style.width = 200;clickMe.style.width = "200px"; clickMe.style.padding = "0.5em";
function okayClick() {this.style.color = "red";this.className = "highlighted"; }
.highlighted { color: red; }
body
(example)<script type="text/javascript"> JavaScript code </script>
head
or body
document.write
document.write("message");
body
document.write
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
arrayfunction 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 a hash table data structurevar 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)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 codealert
to print out variable values and track logic flowconsole.log
function"use strict";
at the start of (top-level) functions to fail on common conditions.
eval
alert
at the top of the filealert
are your friendsvar name = { fieldName: value, ... fieldName: value };
var pt = { x: 4, y: 3 }; alert(pt.x + ", " + pt.y);
Point
object; it has fields named x
and y
typeof(pt) === "object"
var name = { ... methodName: function(parameters) { statements; } };
var pt = {
x: 4, y: 3,
distanceFromOrigin: function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
};
alert(pt.distanceFromOrigin()); // 5
this
this
keyword is mandatory in JSWhat if we want to create an entire new class, not just one object?
// Creates and returns a new Point object. (This is bad code.)
function constructPoint(xValue, yValue) {
var pt = {
x: xValue, y: yValue,
distanceFromOrigin: function() {
return Math.sqrt(this.x * this.x + this.y * this.y;
}
};
return pt;
}
var p = constructPoint(4, -3);
new
syntax we're used to
// 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);
};
}
var p = new Point(4, -3);
new
, JavaScript does the following:
this
within the function
new
?
var p = Point(4, -3);
// 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);
};
}
Point
object has its own entire copy of the distanceFromOrigin
code
Object.prototype
String.prototype
, etc.
undefined
.
// also causes Point.prototype to become defined
function Point(xValue, yValue) {
...
}
Point
constructor, that creates a Point.prototype
Point
object will use Point.prototype
new
, JavaScript does the following:
this
// 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); };
x
and y
fields in Point.prototype
?
distance
and toString
methods.
Point
prototype methods// Computes the distance between this point and the given point p. Point.prototype.distance = function(p) { var dx = this.x - p.x; var dy = this.y - p.y; return Math.sqrt(dx * dx + dy * dy); }; // Returns a text representation of this object, such as "(3, -4)". Point.prototype.toString = function() { return "(" + this.x + ", " + this.y + ")"; };
Point
code could be saved into a file Point.js
toString
method works similarly as in Java// add a 'contains' method to all String objects String.prototype.contains = function(text) { return this.indexOf(text) >= 0; }; // add a 'lightUp' method to all HTML DOM element objects HTMLElement.prototype.lightUp = function() { this.style.backgroundColor = "yellow"; this.style.fontWeight = "bold"; };
reverse
method to strings.
shuffle
method to arrays.
function SuperClassName(parameters) { // "superclass" constructor
...
};
function SubClassName(parameters) { // "subclass" constructor
...
};
SubClassName.prototype = new SuperClassName(parameters); // connect them
SubClassName.prototype = SuperClassName.prototype; // connect them
// Constructor for Point3D "class" function Point3D(x, y, z) { this.x = x; this.y = y; this.z = z; }; Point3D.prototype = new Point(0, 0); // set as "subclass" of Point // override distanceFromOrigin method Point3D.prototype.distanceFromOrigin = function() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); };
super
keyword
<button onclick="okayClick();">OK</button>
// called when OK button is clicked
function okayClick() {
alert("booyah");
}
// where element is a DOM element object
element.event = function;
<button id="ok">OK</button>
document.getElementById("ok").onclick = okayClick;
<head> <script src="myfile.js" type="text/javascript"></script> </head> <body> ... </body>
// global code
var x = 3;
function f(n) { return n + 1; }
function g(n) { return n - 1; }
x = f(x);
script
tag
body
<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: document.getElementById("ok") is 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
<!-- look Ma, no JavaScript! -->
<button id="ok">OK</button>
// 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"); }; };
How would we do each of the following in JavaScript code? Each involves modifying each one of a group of elements ...
div
s of class puzzle
to random x/y locations.ul
list with class
of TAs
to have a gray background.<p> This is a paragraph of text with a <a href="/path/page.html">link in it</a>. </p>
every node's DOM object has the following properties:
name(s) | description |
---|---|
firstChild , lastChild
|
start/end of this node's list of children |
childNodes
|
array of all this node's children |
nextSibling , previousSibling
|
neighboring nodes with the same parent |
parentNode
|
the element that contains this node |
<p id="foo">This is a paragraph of text with a <a href="/path/to/another/page.html">link</a>.</p>
<div> <p> This is a paragraph of text with a <a href="page.html">link</a>. </p> </div>
div
above have?"\n\t"
(before/after the paragraph)a
tag?
document
and other DOM objects (* = HTML5):
name | description |
---|---|
getElementsByTagName
|
returns array of descendents with the given tag, such as "div"
|
getElementsByName
|
returns array of descendents with the given name attribute (mostly useful for accessing form controls)
|
querySelector *
|
returns the first element that would be matched by the given CSS selector string |
querySelectorAll *
|
returns an array of all elements that would be matched by the given CSS selector string |
highlight all paragraphs in the document:
var allParas = document.querySelectorAll("p"); for (var i = 0; i < allParas.length; i++) { allParas[i].style.backgroundColor = "yellow"; }
<body> <p>This is the first paragraph</p> <p>This is the second paragraph</p> <p>You get the idea...</p> </body>
highlight all paragraphs inside of the section with ID "address"
:
// var addrParas = document.getElementById("address").getElementsByTagName("p");
var addrParas = document.querySelectorAll("#address p");
for (var i = 0; i < addrParas.length; i++) {
addrParas[i].style.backgroundColor = "yellow";
}
<p>This won't be returned!</p>
<div id="address">
<p>1234 Street</p>
<p>Atlanta, GA</p>
</div>
name | description |
---|---|
document.createElement("tag")
|
creates and returns a new empty DOM node representing an element of that type |
document.createTextNode("text")
|
creates and returns a text node containing given text |
// create a new <h2> node
var newHeading = document.createElement("h2");
newHeading.innerHTML = "This is a heading";
newHeading.style.color = "green";
Every DOM element object has these methods:
name | description |
---|---|
appendChild(node)
|
places given node at end of this node's child list |
insertBefore(new, old)
|
places the given new node in this node's child list just before old child
|
removeChild(node)
|
removes given node from this node's child list |
replaceChild(new, old)
|
replaces given child with new node |
var p = document.getElementById(document.createElement("p")); p.innerHTML = "A paragraph!"; document.getElementById("main").appendChild(p);
function slideClick() { var bullets = document.getElementsByTagName("li"); for (var i = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("children") >= 0) { bullets[i].parentNode.remove(bullets[i]); } } }
removeChild
method to remove its children from the page
innerHTML
hackingWhy not just code the previous example this way?
function slideClick() { document.getElementById("thisslide").innerHTML += "<p>A paragraph!</p>"; }
"
and '
function slideClick() { this.innerHTML += "<p style='color: red; " + "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>"; }