JavaScript Riddle

by Ronny

HTML

<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"></script>
<script src="https://raw.github.com/LeaVerou/prefixfree/master/prefixfree.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet'>
<form class="question" id="q1">
<p>What will the <code>result</code> variable contain after executing the following code?

<code type="javascript">function foo(x) {
    if (x === 0) return 0;
    if (x === 1) return 1;
    return foo(x-1) + foo(x-2);
}

var result = foo(7);</code>
    <input class="answer">
    <input type="submit">
</form>

<section id="feedback">
    <output id="right">Congrats! You rock!</output>
    <output id="wrong">Oops, that's incorrect. Try again.</output>
</section>

CSS

body, input {font-family: "Open Sans", sans-serif;}

/* Questions */
code {font-family: Consolas, monospace;}
code[type=javascript] {
    display: block;
    margin: 10px auto;
    white-space: pre; white-space: pre-wrap; word-wrap: break-word;
    background: #f9f9f9;
    border: 1px solid #ccc;
    padding: 5px;
}

/* Inputs */
input {
    background: #fcfcfc; border: 1px solid #ccc; padding: 5px;
}
input[type=submit] {
    font-weight: bold; padding: 5px 10px; transition: all 0.2s ease-out;
}
code[type=javascript], input {
    box-shadow: 0 6px 3px -4px rgba(0,0,0,0.08);
}
.question input:hover, .question input:focus + input {
    background: #fff; box-shadow: 0 5px 3px -4px rgba(0,0,0,0.3); border-color: #bbb;
}

/* Outputs */
#feedback {position: relative; overflow: hidden; height: 500px;}
output {
    display: block; position: absolute; top: 0; left: 2px; width: 100%; height: auto;
    padding: 5px; color: #fff; font-weight: bold;
    text-shadow: 0 1px 2px rgba(0,0,0,.6);
    box-shadow: 0 7px 3px -4px rgba(0,0,0,0.12);
    top: -50px;
    transition: all 0.2s ease-out;
}
#right {background: #24bd00;}
#wrong {background: #d20000;}

.right #right, .wrong #wrong {top: 0;}

JavaScript

var $body = $('body'),
    answer;

$('.question').submit(function(e) {
    e.preventDefault();
    var $this = $(this);
    answer = $this.find('input').val();
    var code = $this.find('[type=javascript]').text();
    $('<script>').html(code + '; $(window).trigger("ranCode")').appendTo($body);
});

$(window).bind('ranCode', function() {
    $body.removeAttr('class');
    if (result == answer) {
        $body.addClass('right');
    } else {
        $body.addClass('wrong');
    }
});

// syntax highlighting
$('code').addClass('prettyprint');
prettyPrint();