Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp and Jessica Miller and are licensed under the Creative Commons Attribution 2.5 License.
JavaScript is a powerful language, but it has many flaws:
// check if browser is IE (bad style!)
if (navigator.appName === "Microsoft Internet Explorer") { ...
.value
of many DOM controls (unless set explicitly)
<option value="Bike">Bike</option>
String.split
(some incompatibilities)setTimeout
(some incompatibilities)str[i]
notation
<script src="http://www.cs.washington.edu/education/courses/cse190m/08sp/prototype.js"
type="text/javascript"></script>
<!-- or, -->
<script src="http://prototypejs.org/assets/2008/1/25/prototype-1.6.0.2.js"
type="text/javascript"></script>
abs
,
ceil
,
floor
,
round
,
succ
,
times
,
toColorPart
,
toJSON
,
toPaddedString
clone
,
extend
,
inspect
,
isArray
,
isElement
,
isFunction
,
isHash
,
isNumber
,
isString
,
isUndefined
,
keys
,
toHTML
,
toJSON
,
toQueryString
,
values
blank
,
camelize
,
capitalize
,
dasherize
,
empty
,
endsWith
,
escapeHTML
,
evalJSON
,
evalScripts
,
extractScripts
,
gsub
,
include
,
inspect
,
interpolate
,
isJSON
,
parseQuery
,
scan
,
startsWith
,
strip
,
stripScripts
,
stripTags
,
sub
,
succ
,
times
,
toArray
,
toJSON
,
toQueryParams
,
truncate
,
underscore
,
unescapeHTML
,
unfilterJSON
$("id")
returns the DOM object representing the element with the given id
$$("selector")
returns an array of DOM objects representing elements that match the given CSS selector
Prototype adds the following methods to every DOM element object:
absolutize
,
addClassName
,
addMethods
,
adjacent
,
ancestors
,
childElements
,
classNames
,
cleanWhitespace
,
clonePosition
,
cumulativeOffset
,
cumulativeScrollOffset
,
descendantOf
,
descendants
,
down
,
empty
,
extend
,
fire
,
firstDescendant
,
getDimensions
,
getElementsByClassName
,
getElementsBySelector
,
getHeight
,
getOffsetParent
,
getStyle
,
getWidth
,
hasClassName
,
hide
,
identify
,
immediateDescendants
,
insert
,
inspect
,
makeClipping
,
makePositioned
,
match
,
next
,
nextSiblings
,
observe
,
positionedOffset
,
previous
,
previousSiblings
,
readAttribute
,
recursivelyCollect
,
relativize
,
remove
,
removeClassName
,
replace
,
scrollTo
,
select
,
setOpacity
,
setStyle
,
show
,
siblings
,
stopObserving
,
toggle
,
toggleClassName
,
undoClipping
,
undoPositioned
,
up
,
update
,
viewportOffset
,
visible
,
wrap
,
writeAttribute
function makeFontBigger() { $("text").style.fontSize = parseInt( $("text").getStyle("font-size")) + 2 + "pt"; }
$
function makes accessing elements easygetStyle
function added to DOM object allows accessing existing stylesEvery Javascript program can refer to the following global objects:
document
objectgetElementById
(a.k.a. $
*)getElementsByName
getElementsByTagName
getElementsByClassName
*getElementsBySelector
* (a.k.a. $$
*)close
,
open
,
write
,
writeln
window
objectwindow
objectalert
,
confirm
,
prompt
(popup boxes)
setInterval
,
setTimeout
clearInterval
,
clearTimeout
(timers)
open
,
close
(popping up new browser windows)
blur
,
focus
,
moveBy
,
moveTo
,
print
,
resizeBy
,
resizeTo
,
scrollBy
,
scrollTo
,
window.open
window.open("http://foo.com/bar.html", "My Foo Window", "width=900,height=600,scrollbars=1");
window.open
pops up a new browser windowlocation
objectnavigator
objectnavigator
object to see what browser is being used, and write browser-specific scripts and hacks:
if (navigator.appName === "Microsoft Internet Explorer") { ...
screen
objecthistory
objecthistory
properties, for securityXHTML elements have the following events:
onclick
: user presses/releases mouse button on this elementondblclick
: user presses/releases mouse button twice on this elementonmousedown
: user presses down mouse button on this elementonmouseup
: user releases mouse button on this element onmouseover
: mouse cursor enters this element's boxonmouseout
: mouse cursor exits this element's boxonmousemove
: mouse cursor moves around within this element's box<div onmousemove="myFunction();">...</div>
<div id="target" onmouseover="colorIt();">I'm OVER you!</div>
function colorIt() { $("target").style.backgroundColor = "red"; }
<div id="dare" onmousedown="colorIt();" onmouseup="uncolorIt();"> Click me ... I dare you! </div>
function colorIt() { $("dare").style.backgroundColor = "red"; } function uncolorIt() { $("dare").style.backgroundColor = "white"; }
function colorIt(event) { $("dare").style.backgroundColor = "red"; $("dare").innerHTML = "You clicked (" + event.screenX + ", " + event.screenY + ")"); }
type
: what kind of event, such as "click"
or "mousedown"
on
prefixclientX
, clientY
: coordinates from top/left of pagescreenX
, screenY
: coordinates from top/left of screenevent
as a parameter
window.event
offsetX
, offsetY
: coordinates from top/left of element
layerX
, layerY
properties insteadbutton
: which mouse button was pressed/released, if any
which
property insteadsrcElement
: element that fired the event
target
property instead
function name(event) {
Event.extend(event);
...
}
Event.extend
repairs many event incompatibilities:element
(replaces which
/ srcElement
properties)isLeftClick
(replaces button
/ which
properties)pointerX
,
pointerY
(replace clientX
, clientY
properties)
findElement
,
stop
,
stopObserving
,
unloadCache
DOM objects for HTML elements have the following properties:
onkeydown
: user presses a key while this element has keyboard focusonkeyup
: user releases a key while this element has keyboard focusonkeypress
: user presses and releases a key while this element has keyboard focusonfocus
: this element gains keyboard focusonblur
: this element loses keyboard focuskeyCode
: ASCII numeric value of key that was pressed
String.fromCharCode(event.keyCode)
altKey
: true
if Alt key is being heldctrlKey
: true
if Ctrl key is being heldshiftKey
: true
if Shift key is being heldWhich key event properties does your browser support?
function name(event) {
Event.extend(event);
...
}
Event.extend
adds these useful key code constants:
Event.KEY_BACKSPACE
,
Event.KEY_DELETE
,
Event.KEY_DOWN
,
Event.KEY_END
,
Event.KEY_ESC
,
Event.KEY_HOME
,
Event.KEY_LEFT
,
Event.KEY_PAGEDOWN
,
Event.KEY_PAGEUP
,
Event.KEY_RETURN
,
Event.KEY_RIGHT
,
Event.KEY_TAB
,
Event.KEY_UP
,
<input type="text" onkeypress="keyPress();" />
function keyPress(event) {
Event.extend(event);
if (event.keyCode == Event.KEY_RETURN) {
// the user pressed Enter
alert("You pressed the Enter key!");
}
}
these are supported by <input type="text">
, <textarea>
One of the coolest features of Google Maps is the ability to drag the map to move it around. Write a program with a draggable map of Middle Earth using Javascript mouse event handlers. (See the background CSS properties from the end of the CSS slides.)