#MonthOfCode - Day 1: hello world

My entry for the 1st day of the month of code. The theme for today is: hello world.

Code after the break.

hello-world.jsview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
(function() {

var el = document.getElementById('moc-1');
var source = '#monthofcode';
var target = 'hello world!';
var alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789#! ';

function animate(src, tgt, done) {
function step() {
if (src === tgt) {
return done();
}
var nextSrc = '';
for (var i = 0; i < src.length; i++) {
// increment each letter if target not reached
if (src.charAt(i) !== tgt.charAt(i)) {
var nextIndex = alphabet.indexOf(src.charAt(i)) + 1;
nextIndex %= alphabet.length;
nextSrc += alphabet.charAt(nextIndex);
} else {
nextSrc += src.charAt(i);
}
}
el.innerHTML = nextSrc;
src = nextSrc;
setTimeout(step, 120);
}
step();
}

function run() {
animate(source, target, function done() {
// swap target and source for next iteration
var tmp = source;
source = target;
target = tmp;

setTimeout(run, 2000);
});
}
run();

})();