Attribution:Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. 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.
Otherwise noted: Claude Anderson was given permission to modify the slides for CSSE 290 at Rose-Hulman by author Jessica Miller.
The authors' original slides, based on Web Programming Step by Step, can be seen at http://webstepbook.com.
Some of the examples in some days' slides are from David Fisher at Rose-Hulman, who was kind enough to allow me to use them.
My intention is to mark these examples with [DSF].
<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;
alert("message"); // message confirm("message"); // returns true or false prompt("message"); // returns user input string
abort
|
blur
|
change
|
click
|
dblclick
|
error
|
focus
|
keydown
|
keypress
|
keyup
|
load
|
mousedown
|
mousemove
|
mouseout
|
mouseover
|
mouseup
|
reset
|
resize
|
select
|
submit
|
unload
|
click
event (onclick
) is just one of many events that can be handled
method | description |
---|---|
setTimeout(function, delayMS);
|
arranges to call given function after given delay in ms |
setInterval(function, delayMS);
|
arranges to call function repeatedly every delayMS ms |
clearTimeout(timerID); clearInterval(timerID);
|
stops the given timer so it will not call its function |
setTimeout
and setInterval
return an ID representing the timer
clearTimeout
/Interval
later to stop the timer
setTimeout
example
<button onclick="delayMsg();">Click me!</button> <span id="output"></span>
function delayMsg() {
setTimeout(booyah, 5000);
document.getElementById("output").innerHTML = "Wait for it...";
}
function booyah() { // called when the timer goes off
document.getElementById("output").innerHTML = "BOOYAH!";
}
setInterval
example
var timer = null; // stores ID of interval timer function delayMsg2() { if (timer == null) { timer = setInterval(rudy, 1000); } else { clearInterval(timer); timer = null; } } function rudy() { // called each time the timer goes off document.getElementById("output").innerHTML += " Rudy!"; }
function delayedMultiply() {
// 6 and 7 are passed to multiply when timer goes off
setTimeout(multiply, 2000, 6, 7);
}
function multiply(a, b) {
alert(a * b);
}
setTimeout(multiply(6 * 7), 2000);
()
when passing the function
setTimeout(booyah(), 2000);setTimeout(booyah, 2000);setTimeout(multiply(num1 * num2), 2000);setTimeout(multiply, 2000, num1, num2);
()
?JavaScript is a powerful language, but it has many flaws:
<script src="../scripts/prototype.js" type="text/javascript"></script>
Put the above script
element before the one that links to your own JavaScript code.
$
function
$("id")
id
document.getElementById("id")
getElementByID
$("footer").innerHTML = $("username").value.toUpperCase();
method(s) | description |
---|---|
ancestors ,
up
|
elements above this one |
childElements ,
descendants ,
down
|
elements below this one (not text nodes) |
siblings ,
next ,
nextSiblings , previous ,
previousSiblings ,
adjacent
|
elements with same parent as this one (not text nodes) |
// alter siblings of "main" that do not contain "Sun"
var sibs = $("main").siblings();
for (var i = 0; i < sibs.length; i++) {
if (sibs[i].innerHTML.indexOf("Sun") < 0) {
sibs[i].innerHTML += " Sunshine";
}
}
Prototype adds methods to document
(and all DOM elements) for selecting groups of elements:
getElementsByClassName
|
array of elements that use given class attribute
|
select
|
array of descendants that match given CSS selector, such as "div#sidebar ul.news > li"
(identical to querySelectorAll on the element)
|
$$
|
Equivalent to document.querySelectorAll
|
var gameButtons = $("game").select("button.control"); for (var i = 0; i < gameButtons.length; i++) { gameButtons[i].style.color = "yellow"; }
$$
function
var arrayName = $$("CSS selector");
// hide all "announcement" paragraphs in the "news" section
var paragraphs = $$("div#news p.announcement");
for (var i = 0; i < paragraphs.length; i++) {
paragraphs[i].hide();
}
$$
Returns an array of DOM elements that match the given CSS selector
$
but returns an array instead of a single DOM object
document.select
$$
Issues.
or #
in front of a class
or id
// get all buttons with a class of "control" var gameButtons =$$("control");var gameButtons = $$(".control");
$$
returns an array, not a single element; must loop over the results
// set all buttons with a class of "control" to have red text$$(".control").style.color = "red";var gameButtons = $$(".control"); for (var i = 0; i < gameButtons.length; i++) { gameButtons[i].style.color = "red"; }
$$
even if my CSS file doesn't have any style rule for that same group? (A: Yes!)
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.removeChild(bullets[i]); } } }
removeChild
method to remove any of its children from the page
function slideClick() { var bullets = $$("li"); for (var i = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("children") >= 0) { bullets[i].remove(); } } }
removeChild
method to remove its children from the page
remove
method to elements it returns
Pair-program this with your partner (do it on one computer)
Click a word, and all occurrences of that word get highlighted
I have provided a PHP file that delives the text. Read and discuss it together, but you should not have to change it.
innerHTML
hackingWhy not just code the previous example this way?
function slideClick() { $("thisslide").innerHTML += "<p>A paragraph!</p>"; }
"
and '
function slideClick() { $("main").innerHTML += "<p style='color: red; " + "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>"; }
innerHTML
function slideClick() { var p = document.createElement("p"); p.className = "special"; p.onclick = myOnClick; p.innerHTML = "A paragraph!"; $("thisslide").appendChild(p); }
.special { color: red; margin-left: 50px; }
<button id="clickme">Click Me</button>
window.onload = function() { $("clickme").onclick = biggerFont; }; function biggerFont() { var size = parseInt($("clickme").style.fontSize); size += 4; $("clickMe").style.fontSize = size + "pt"; }
style
property lets you set any CSS style for an element
function biggerFont() {
// make the text bigger
var size = parseInt($("clickme").getStyle("font-size"));
$("clickme").style.fontSize = (size + 4) + "pt";
}
getStyle
method (added to each DOM object by Prototype) allows accessing existing styles$("main").style.top = $("main").getStyle("top") + 100 + "px";// bad!
"200px" + 100 + "px"
, "200px100px"
$("main").style.top = parseInt($("main").getStyle("top")) + 100 + "px"; // correct
function highlightField() {
// turn text yellow and make it bigger
if (!$("text").className) {
$("text").className = "highlight";
} else if ($("text").className.indexOf("invalid") < 0) {
$("text").className += " highlight";
}
}
className
property corresponds to HTML class
attribute
function highlightField() {
// turn text yellow and make it bigger
if (!$("text").hasClassName("invalid")) {
$("text").addClassName("highlight");
}
}
addClassName
,
removeClassName
,
toggleClassName
,
hasClassName
manipulate CSS classesclassName
DOM property, but don't have to manually split by spaces
classList
property, allows similar manipulations, but is clunkier.