Quiz Timer

jQuery stopwatch which begins on user focus, stops on focus out and begins a new timer. A solution for this StackOverflow question: http://stackoverflow.com/q/6090514/66580

by majidf

HTML

<table class="basic">
    <tr>
        <td>3</td>
        <td> x </td>
        <td>5</td>
        <td> =   <input type="text" class="field" name="user_response0"id="u_r0" /></td>
        <td id="timer_0"></td>
    </tr>
    <tr>
        <td>14</td>
        <td> / </td>
        <td>2</td>
        <td> =   <input type="text" class="field" name="user_response1"id="u_r1" /></td>
        <td id="timer_1"></td>
    </tr>
    <tr>
        <td>6</td>
        <td> ^ </td>
        <td>2</td>
        <td> = <input type="text" class="field" name="user_response2"id="u_r2" /></td>
        <td id="timer_2"></td>
    </tr>
</table>

<!-- this is for info box only -->
<div><br/><hr/>A solution for <a href="http://stackoverflow.com/q/6090514/66580">this question</a>.</div>

CSS

.active_input { background-color: yellow; }

JavaScript

var timer_id;

$(document).ready(function() {
    $('.field').focus(function() {
        $(this).addClass('active_input');
        timer_id = setInterval('tick()', 1000);
    }).blur(function() {
        $(this).removeClass('active_input');
        clearTimeout(timer_id);
    });
});

function tick() {
    var id_n = $('.active_input').attr('id').substring(3);
    var t_td = $('#timer_' + id_n);
    var t = parseInt(t_td.text(), 10);
    if (isNaN(t)) {
        t = '1 second';
    } else {
        t++;
        t += ' seconds';
    }
    t_td.text(t);
}