As with most my other crib sheet pages, this is a quick reference for
javascript for myself, which I am leaving available on the net. It has
things I need from time to time, and is not meant to be a comprehensive resource.
It is a combination of my own discoveries as well as
information gathered around the net. One large source for this Douglas
Crockford's video classes on javascript and DOM available at
http://developer.yahoo.com/yui/theater/
DOM
Set Class & Style Values
node.className = ...
node.style.styleName = ...
Find current values
IE: node.currentStyle.stylename
Others: document.defaultView().getComputedStyle( node, "" ).getPropertyValue( stylename );
Creating Non-Table Elements
var n = document.createElement(tagName);
var t = document.createTextNode( text );
Creating Table Elements
trObj = table.insertRow( pos );
tdObj = tableRow.insertCell( pos );
Unlike node creation, these actually insert the object.
A pos of -1 inserts at the end.
Adding / Removing nodes to the tree
parent.appendChild( new );
parent.insertBefore( new, child );
parent.replaceChild( new, old );
parent.removeChild( old );
Parent can be found as child.parentNode
Events
Types
blur, change, keydown, keypress, keyup, reset, submit, focus
click, dblclick, mousedown, mousemove, mouseout, mouseover, mouseup
Setting handler
- Legacy:
obj[ "on" + type ] = func;
- IE:
obj.attachEvent( "on" + type, func );
- W3C:
obj.addEventListener( type, f, false );
Handler template
Gets common variables in a browser compatible way
function handler(e) {
if (!e) e = event;
var target = e.target || e.srcElement;
...
}
Cancel Event (bubbling)
e.cancelBubble = true;
if ( e.stopPropogation ) {
e.stopPropogation();
}
Cancel Default Action
e.returnValue = false;
if ( e.preventDefault ) {
e.preventDefault();
}
return false;
Exceptions
An exception can be any created object with the fields
name
and message
. When checking exceptions,
the name field can be used to find the type you are interested in.
Names used with in Javascript, which can be created using new
Name(msg)
Error, EvalError, RangeError,
SyntaxError, TypeError, URIError
Creating your own
throw { name:"MyError", message:"Failed to ..." };