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="http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
$
function
$("id")
id
document.getElementById("id")
$("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";
}
}
()
document
and other DOM objects for accessing descendents:
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)
|
Prototype adds methods to the document
object (and all DOM element objects) 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"
|
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!)
<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() {
// turn text yellow and make it bigger
var size = parseInt($("clickme").getStyle("font-size"));
$("clickme").style.fontSize = (size + 4) + "pt";
}
getStyle
function added to DOM object allows accessing existing stylesaddClassName
, removeClassName
, hasClassName
manipulate CSS classesthis.style.top = this.getStyle("top") + 100 + "px";// bad!
"200px" + 100 + "px"
, "200px100px"
this.style.top = parseInt(this.getStyle("top")) + 100 + "px"; // correct
function highlightField() {
// turn text yellow and make it bigger
if (!$("text").hasClassName("invalid")) {
$("text").addClassName("highlight");
}
}
addClassName
, removeClassName
, hasClassName
manipulate CSS classesclassName
DOM property, but don't have to manually split by spaces
$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(); }
<form id="exampleform" action="http://foo.com/foo.php">...</form>
window.onload = 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();
return false;
}
}
stop
method on the eventClass.create
method makes a new class of objects
className = Class.create({
// constructor
initialize : function(parameters) {
this.fieldName = value;
...
},
methodName : function(parameters) {
statements;
},
...
});
initialize
functionClass.create
examplePoint = Class.create({ // Constructs a new Point object at the given initial coordinates. initialize: function(initialX, initialY) { this.x = initialX; this.y = initialY; }, // Computes the distance between this Point and the given Point p. 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 Point object. toString: function() { return "(" + this.x + ", " + this.y + ")"; } });
className = Class.create(superclass, { ... });
// Points that use "Manhattan" (non-diagonal) distances. ManhattanPoint = Class.create(Point, { // Computes the Manhattan distance between this Point and p. // Overrides the distance method from Point. distance: function(p) { var dx = Math.abs(this.x - p.x); var dy = Math.abs(this.y - p.y); return dx + dy; }, // Computes this point's Manhattan Distance from the origin. distanceFromOrigin: function() { return this.x + this.y; } });
$super
name: function($super, parameters) { statements; }
ManhattanPoint3D = Class.create(ManhattanPoint, {
initialize: function($super, initialX, initialY, initialZ) {
$super(initialX, initialY); // call Point constructor
this.z = initialZ;
},
// Returns 3D "Manhattan Distance" from p.
distance: function($super, p) {
var dz = Math.abs(this.z - p.z);
return $super(p) + dz;
},
});
$super
in codeClass.create
method to make the Movie
type.
FancyMovie
that displays its movie ratings as star images rather than just showing a number on the page.
Scriptaculous : a JavaScript library, built on top of Prototype, that adds:
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script> <script src="http://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)
element.effectName(); // for most effects // some effects must be run the following way: new Effect.name(element or id);
$("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
$("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
, finishOn
Shrink
) are technically "parallel effects", so to access the modified element, you write effect.effects[0].element
rather than just effect.element
Scriptaculous provides several objects for supporting drag-and-drop functionality:
Draggable
: an element that can be draggedDraggables
: manages all Draggable
objects on the pageDroppables
: elements on which a Draggable
can be droppedSortable
: a list of items that can be reorderedDraggable
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. Default options.</div> <div id="draggabledemo2">Draggable demo. {snap: [40,40], revert: true}</div>
document.observe("dom:loaded", function() { new Draggable("draggabledemo1"); new Draggable("draggabledemo2", {revert: true, snap: [40, 40]}); });
Draggables
drags
,
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="product1" src="images/shirt.png" alt="shirt" /> <img id="product2" src="images/cup.png" alt="cup" /> <div id="droptarget"></div>
document.observe("dom:loaded", function() { new Draggable("product1"); new Draggable("product2"); Droppables.add("droptarget", {onDrop: productDrop}); }); function productDrop(drag, drop, event) { alert("You dropped " + drag.id); }
Sortable
Sortable.create(element or id of list, { options } );
ul
, ol
) as being able to be dragged into any orderDraggable
s and Droppable
stag
,
only
,
overlap
,
constraint
,
containment
,
format
,
handle
,
hoverclass
,
ghosting
,
dropOnEmpty
,
scroll
,
scrollSensitivity
,
scrollSpeed
,
tree
,
treeTag
Sortable.destroy
on itSortable
demo<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>
document.observe("dom:loaded", function() { Sortable.create("simpsons"); });
Sortable
list eventsevent | 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 itScriptaculous 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
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
, ignoreCase
Autocompleter.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 } );
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);