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.
JavaScript is a powerful language, but it has many flaws:
<script src="libraryURL" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"
type="text/javascript"></script>
String, Array, Date, Number, ObjectArray:
clear,
clone,
compact,
first,
flatten,
indexOf,
inspect,
intersect,
last,
lastIndexOf,
reverse,
uniq,
without
Date:
toISOString,
toJSON
Enumerable (arrays/objects):
all,
any,
each,
eachSlice,
filter,
find,
grep,
inGroupsOf,
inject,
inspect,
map,
max,
member,
min,
partition,
pluck,
reject,
select,
size,
toArray,
zip
Function:
argumentNames,
bind,
bindAsEventListener,
curry,
defer,
delay,
methodize,
wrap
Number:
abs,
ceil,
floor,
round,
succ,
times,
toColorPart,
toPaddedString
Object:
clone,
extend,
inspect,
isArray,
isDate,
isElement,
isFunction,
isHash,
isNumber,
isString,
isUndefined,
keys,
toHTML,
toJSON,
toQueryString,
values
RegExp:
escape,
match
String:
blank,
camelize,
capitalize,
dasherize,
empty,
endsWith,
escapeHTML,
evalJSON,
gsub,
interpolate,
isJSON,
parseQuery,
scan,
startsWith,
strip,
stripTags,
sub,
succ,
times,
toArray,
toQueryParams,
truncate,
underscore,
unescapeHTML,
unfilterJSON,
$ function
$("id")
$ returns the DOM object representing the element with the given id
document.getElementById("id")
$("footer").innerHTML = $("username").value.toUpperCase();
$$ function
var arrayName = $$("CSS selector");
$$ returns an array of DOM elements that match the given CSS selector
document.querySelectorAll
querySelectorAll became widely supported (a recent addition to browsers) and also works on older browsers
// 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();
}
$F("formID")["name"]
$F("controlID")
$F function returns the value of a form control with the given id
if ($F("username").length < 4) {
$("username").clear();
$("login").disable();
}
Prototype adds the following methods to every DOM element object:
| 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";
}
}
each paradigm
// alter siblings of "main" that do not contain "Sun" $$("div#main ul > li.new").each(function(e) { // add a class to some elements e.classList.add("exciting"); }); $$("div#main ul > li.old").each(Element.hide); // hide all 'old' elements
$$ and looping over them, you call each on the list of results and pass a function to call on each element that was matched
Element methods
<button id="clickme">Click Me</button>
function biggerFont() {
// turn text yellow and make it bigger
var size = $("clickme").getStyle("font-size"); // "22px"
$("clickme").style.fontSize = parseInt(size) + 4 + "pt";
}
getStyle function added to DOM object allows accessing existing styles
.style.propertyName, it will often return an empty string)addClassName, removeClassName, hasClassName manipulate CSS classeselement.onevent = function; element.observe("event", function);
// call the playNewGame function when the Play button is clicked
$("play").observe("click", playNewGame);
observe method (added by Prototype)
observe substitutes for addEventListener (not supported by old versions of IE)
| property/method | description |
|---|---|
pointerX(), * pointerY()
|
coordinates in entire web page (replaces pageX, pageY)
|
isLeftClick(), ** isMiddleClick(), isRightClick()
|
true if left/mid/right button was pressed (replaces button and which)
|
$("game").observe("mousemove", move);
function move(event) {
if (event.isLeftClick() &&
event.pointerX() < this.getWidth() / 2) {
gameOver();
}
}
Event.KEY_BACKSPACE
|
Event.KEY_DELETE
|
Event.KEY_ESC
|
Event.KEY_RETURN
|
Event.KEY_TAB
|
Event.KEY_DOWN,Event.KEY_LEFT,Event.KEY_RIGHT,Event.KEY_UP
|
Event.KEY_HOME,Event.KEY_END
|
Event.KEY_PAGEDOWN,Event.KEY_PAGEUP
|
$("game").observe("keydown", typing);
function typing(event) {
if (event.keyCode() == Event.KEY_ESC) {
quitGame();
}
}
window.onload (runs before images download):
window.onload = function() { ... };document.observe("dom:loaded", function() { // attach event handlers, etc. });
activate |
clear |
disable |
enable |
focus |
getValue |
present |
select |
<form id="exampleform" action="http://foo.com/foo.php">...</form>
document.observe("dom:loaded", function() {
$("exampleform").observe("submit", checkData);
});
function checkData(event) {
if ($F("city") == "" || $F("state").length != 2) {
alert("Error, invalid city/state."); // show error message
event.stop();
}
}
stop method on the event
new Ajax.Request("url", {
option : value,
option : value,
...
option : value
});
Ajax.Request object to request a page from a server using Ajax
XMLHttpRequest and adds some new features{} braces
(an anonymous JS object)
| option | description |
|---|---|
method
|
how to fetch the request from the server (default "post")
|
asynchronous
|
should request be sent asynchronously in the background? (default true)
|
parameters
|
query parameters to pass to the server, if any (as a string or object) |
onSuccess
|
event: request completed successfully |
onFailure
|
event: request was unsuccessful |
onException
|
event: request has a syntax error, security error, etc. |
others: contentType, encoding,
requestHeaders; events: onCreate, onComplete,
on### (for HTTP error code ###)
|
|
new Ajax.Request("foo/bar/mydata.txt", {
method: "get",
onSuccess: myAjaxSuccessFunction
});
...
function myAjaxSuccessFunction(ajax) {
do something with ajax.responseText;
}
onSuccess eventajax| property | description |
|---|---|
status
|
the request's HTTP result code (200 = OK, etc.) |
statusText
|
HTTP status code text |
responseText
|
the entire text of the fetched file, as a string |
responseXML, responseJSON
|
the entire contents of the fetched file, in other formats (seen later) |
function myAjaxSuccessFunction(ajax) {
alert(ajax.responseText);
}
responseText, to access the fetched text content
new Ajax.Request("url", {
method: "get",
onSuccess: functionName,
onFailure: ajaxFailure,
onException: ajaxFailure
});
...
function ajaxFailure(ajax, exception) {
alert("Error making Ajax request:" +
"\n\nServer status:\n" + ajax.status + " " + ajax.statusText +
"\n\nServer response text:\n" + ajax.responseText);
if (exception) {
throw exception;
}
}
new Ajax.Request("lookup_account.php", {
method: "get",
parameters: {name: "Ed Smith", age: 29, password: "abcdef"},
onFailure: ajaxFailure,
onException: ajaxFailure
});
...
"?" + ...
parameters object, {} braces with name : value pairs
"name=Ed+Smith&age=29&password=abcdef")POST request
new Ajax.Request("url", {
method: "post",
parameters: {name: value, name: value, ..., name: value},
onSuccess: functionName,
onFailure: functionName,
onException: functionName
});
method should be changed to "post" (or omitted; post is default)FormData object
new Ajax.Updater("id", "url", {
method: "get"
});
Ajax.Updater fetches a file and injects its content into an element as innerHTML
Ajax.Request, but Ajax.Updater saves you some typing and workid of element to inject intoonSuccess handler not needed (but onFailure, onException handlers may still be useful)
new Ajax.Updater({success: "id", failure: "id"}, "url", {
method: "get",
insertion: "top"
});
success and/or failure id
success element will be filled if the request succeedsfailure element (if provided) will be filled if the request failsinsertion parameter specifies where in the element to insert the text (top, bottom, before, after)
new Ajax.PeriodicalUpdater("id", "url", {
frequency: seconds,
name: value, ...
});
Ajax.PeriodicalUpdater repeatedly fetches a file at a given interval and injects its content into an element as innerHTMLonSuccess handler not needed (but onFailure, onException handlers may still be useful)Ajax.Updater can be passed
Ajax.Responders.register({
onEvent: functionName,
onEvent: functionName,
...
});
Scriptaculous : a JavaScript library, built on top of Prototype, that adds:
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"
type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js"
type="text/javascript"></script>
.js files to your project folder
(appearing)
(disappearing)
(Getting attention)
Click effects above
element.effectName(); // for most effects
new Effect.Name(element or id); // for some effects
$("sidebar").shake();
var buttons = $$("results > button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].fade();
}
element.effectName({
option: value,
option: value,
...
});
$("my_element").pulsate({
duration: 2.0,
pulses: 2
});
{})delay,
direction,
duration,
fps,
from,
queue,
sync,
to,
transition
morph effect
element.morph("CSS", {
option: value,
option: value,
...
});
$("okaybutton").morph("color: #ff0000; width: 300px", {duration: 3.0});
morph effect lets you apply any change of CSS to an element as a gradual animation
$("my_element").fade({
duration: 3.0,
afterFinish: displayMessage
});
function displayMessage(effect) {
alert(effect.element + " is done fading now!");
}
beforeStart,
beforeUpdate,
afterUpdate,
afterFinish
afterFinish event fires once the effect is done animating
Effect object as its parameter
element, options, currentFrame, startOn, finishOnShrink) are technically "parallel effects", so to access the modified element, you write effect.effects[0].element rather than just effect.elementScriptaculous provides several objects for supporting drag-and-drop functionality:
Sortable : a list of items that can be reorderedDraggable : an element that can be draggedDraggables : manages all Draggable objects on the pageDroppables : elements on which a Draggable can be droppedSortable
Sortable.create(element or id of list, {
options
});
ul, ol) as being able to be dragged into any orderDraggables and Droppablestag,
only,
overlap,
constraint,
containment,
format,
handle,
hoverclass,
ghosting,
dropOnEmpty,
scroll,
scrollSensitivity,
scrollSpeed,
tree,
treeTag
Sortable.destroy on itSortable demo<ol id="simpsons"> <li>Homer</li> <li>Marge</li> <li>Bart</li> <li>Lisa</li> <li>Maggie</li> </ol>
document.observe("dom:loaded", function() {
Sortable.create("simpsons");
});
Sortable list events| event | description |
|---|---|
onChange
|
when any list item hovers over a new position while dragging |
onUpdate
|
when a list item is dropped into a new position (more useful) |
document.observe("dom:loaded", function() {
Sortable.create("simpsons", {
onUpdate: listUpdate
});
});
onChange handler function receives the dragging element as its parameteronUpdate handler function receives the list as its parameterSortable list events example
document.observe("dom:loaded", function() {
Sortable.create("simpsons", {
onUpdate: listUpdate
});
});
function listUpdate(list) {
// can do anything I want here; effects, an Ajax request, etc.
list.shake();
}
Sortable eventsonUpdate to work, each li must have an id of the form listID_index
<ol id="simpsons"> <li id="simpsons_0">Homer</li> <li id="simpsons_1">Marge</li> <li id="simpsons_2">Bart</li> <li id="simpsons_3">Lisa</li> <li id="simpsons_4">Maggie</li> </ol>
Sortable.create on the list again to fix itDraggable
new Draggable(element or id, {
options
});
handle,
revert,
snap,
zindex,
constraint,
ghosting,
starteffect,
reverteffect,
endeffect
onStart,
onDrag,
onEnd
Draggable object, and the mouse eventDraggable example
<div id="draggabledemo1">Draggable demo 1. Default options.</div>
<div id="draggabledemo2">Draggable demo 2.
{snap: [40,40], revert: true}</div>
document.observe("dom:loaded", function() {
new Draggable("draggabledemo1");
new Draggable("draggabledemo2", {revert: true, snap: [40, 40]});
});
Draggable demo 1.
Draggable demo 2.Draggablesdrags,
observers
register,
unregister,
activate,
deactivate,
updateDrag,
endDrag,
keyPress,
addObserver,
removeObserver,
notify
Droppables
Droppables.add(element or id, {
options
});
accept,
containment,
hoverclass,
overlap,
greedy
onHover,
onDrop
Draggable, the Droppable, and the event<img id="shirt" src="images/shirt.png" alt="shirt" /> <img id="cup" src="images/cup.png" alt="cup" /> <div id="droptarget"></div>
document.observe("dom:loaded", function() {
new Draggable("shirt");
new Draggable("cup");
Droppables.add("droptarget", {onDrop: productDrop});
});
function productDrop(drag, drop, event) {
alert("You dropped " + drag.id);
}
Scriptaculous offers ways to make a text box that auto-completes based on prefix strings *:
Autocompleter.Local :
auto-completes from an array of choices
Ajax.Autocompleter :
fetches and displays list of choices using Ajax
* (won't be necessary once HTML5 datalist element is well supported)
Autocompleter.Local
new Autocompleter.Local(
element or id of text box,
element or id of div to show completions,
array of choices,
{ options }
);
div to store the auto-completion matches
ul that you can style with CSSclass of selected{ }
choices, partialSearch, fullSearch, partialChars, ignoreCaseAutocompleter.Local demo<input id="bands70s" size="40" type="text" /> <div id="bandlistarea"></div>
document.observe("dom:loaded", function() {
new Autocompleter.Local(
"bands70s",
"bandlistarea",
["ABBA", "AC/DC", "Aerosmith", "America", "Bay City Rollers", ...],
{}
);
});
<input id="bands70s" size="40" type="text" /> <div id="bandlistarea"></div>
#bandlistarea {
border: 2px solid gray;
}
/* 'selected' class is given to the autocomplete item currently chosen */
#bandlistarea .selected {
background-color: pink;
}
Ajax.Autocompleter
new Ajax.Autocompleter(
element or id of text box,
element or id of div to show completions,
url,
{ options }
);
ul with li elements in itparamName,
tokens,
frequency,
minChars,
indicator,
updateElement,
afterUpdateElement,
callback,
parameters
Ajax.InPlaceEditor
new Ajax.InPlaceEditor(element or id,
url,
{ options }
);
Makes it possible to edit the content of elements on a page "live" and send the edits back to the server using Ajax.
okButton,
okText,
cancelLink,
cancelText,
savingText,
clickToEditText,
formId,
externalControl,
rows,
onComplete,
onFailure,
cols,
size,
highlightcolor,
highlightendcolor,
formClassName,
hoverClassName,
loadTextURL,
loadingText,
callback,
submitOnBlur,
ajaxOptions
onEnterHover,
onLeaveHover,
onEnterEditMode,
onLeaveEditMode
Ajax.InPlaceCollectionEditor
new Ajax.InPlaceCollectionEditor(element or id, url, {
collection: array of choices,
options
});
Ajax.InPlaceEditor that gives a collection of choicescollection option whose value is an array of strings to choose fromAjax.InPlaceEditor| method | description |
|---|---|
Sound.play("url");
|
plays a sound/music file |
Sound.disable();
|
stops future sounds from playing (doesn't mute any sound in progress) |
Sound.enable();
|
re-enables sounds to be playable after a call to Sound.disable()
|
Sound.play("music/java_rap.mp3");
Sound.play("music/wazzaaaaaap.wav");
Sound.play('', {replace: true});
new Control.Slider("id of knob", "id of track", {options});
Builder - convenience class to replace document.createElement :
var img = Builder.node("img", {
src: "images/lolcat.jpg",
width: 100, height: 100,
alt: "I can haz Scriptaculous?"
});
$("main").appendChild(img);