Adapted from the HeadFirst JavaScript book. Works in JSFiddle.