Articles

Javascript

These are my Javascript notes and useful links, updated and expanded as I do javascript-ish stuff. I am not sure it can be considered a javascript cheat sheet, but in a way it is, I guess...

General reference

Selectors / finding elements

Apart from the usual getElementById

  • getElementsByClassName
  • getElementsByTagName
  • querySelector and querySelectorAll (javascript 1.8+, i.e. Firefox 3.5+)

querySelector/querySelectorAll examples (or why you won't need jQuery in the future!):


var special = document.querySelectorAll("p.warning, p.note"); 
var el = document.querySelector("#main, #basic, #exclamation");

More info here.

Dimensions

Element dimensions

  • clientWidth, clientHeight: dimensions of visible part of an element, including padding but no borders or scrollbars
  • offsetWidth, offsetHeight: total dimensions of an element, including padding, borders and scrollbars

More info + example graphs here.

Safe window dimensions


var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);

from this snippet.

Positions

Useful properties of an element:

  • offsetLeft: horizontal offset position of the current element relative to its offset container
  • offsetTop: vertical offset position of the current element relative to its offset container
  • offsetParent: offset container of the current element

Get the accumulated 'absolute' position of an element


var left = 0;
var top = 0;
if (obj.offsetParent)
{
    do {
        left += obj.offsetLeft;
        top += obj.offsetTop;
    } while(obj = obj.offsetParent)
}

Courtesy of mr. ppk

Styles

Element styles

Can be accessed via element.style.property; they are equivalent to html inline styles. They won't return values for properties which are specified in CSS rules (e.g. if a class defined background to be red, and the class is applied to an element, element.style.background won't return any reference to that red colour). But if the property is specified inline or using element.style before, they will return a value.

Browser specific properties begin with their own suffix. E.g. Moz-, Webkit-.

Some examples of available properties (NOTE: dashes in css style names get converted to camelCase style names): background, backgroundAttachment, backgroundColor, backgroundImage, backgroundPosition, backgroundRepeat, border, borderBottom...

Longer list here

Actual / computed styles


var style = window.getComputedStyle(element, pseudoElt);

// or another example:
var elem = document.getElementById("elem_container");
var theCSSprop = document.defaultView.getComputedStyle(elem, null).getPropertyValue("height");

returned value is a CSSStyleDeclaration and has various attributes and methods to access its properties:

Attributes: cssText (parsable textual representation of the declaration block), length (number of properties that have been explicitly set in this declaration block), parentRule (the CSS rule that contains this declaration block or null if this CSSStyleDeclaration is not attached to a CSSRule. (note: must look for an example))

Most useful methods: getPropertyCSSValue(propertyName), removeProperty(propertyName), setProperty(propertyName, value, priority)

More info on getComputedStyle

Transformations

More information: Mozilla Transformations

Events


// Register event listener. All arguments are mandatory.
target.addEventListener(type, listener, useCapture);

// Remove event listener
element.removeEventListener(type, listener, useCapture);

More info: addEventListener and removeEventListener

Event types: click, mousedown, mouseup, mouseover, mousemove, mouseout, load, unload, abort, error, select, change, submit, reset, focus, blur, resize, scroll

Some events apply only to some types of element!

More info: very technical and less technical and slightly outdated but easier to understand (note: don't use the 'on' prefix when adding listeners)

To track global key presses


window.addEventListener('keypress', handleKeypress, false);

Intervals / Timers


// Setting up intervals (delay is in milliseconds)
intervalID = window.setInterval(func, delay[, param1, param2, ...]);
intervalID = window.setInterval(code, delay); // code = string of code to be executed each time

// Seting intervals up with anonymous functions
intervalID = setInterval(function() { funcflashText(); }, 1000);  

// Removing them
window.clearInterval(intervalID)

// Setting timers (one off events)
timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
timeoutID = window.setTimeout(code, delay);

// Cancel timer
window.clearTimeout(timeoutID);

More info