Search code examples
javascriptjquerycountkeystrokeonkeydown

simple javascript keystroke count


I'm developing an online study/survey where I need to count the number of keystrokes that a participant makes. I am asking them to type lrlrlrlrlrlrl... in a text field to simulate walking. Turns out many of the participants (as evidenced by the time spent on the task) are copying and pasting.

I need something that will count keystrokes so I can identify participants who completed the task as requested. The study is programmed in Coldfusion and I was thinking about some sort of javascript/onkeydown/hidden file field combination, but I am not really a programmer.

Any help would be appreciated. Thanks.


Solution

  • http://jsfiddle.net/kBJGM/

    HTML:

    <input type="text" class="nopaste"/>
    <input type="text" id="countstroke"/>
    <span id="count"></span>​
    

    Javascript:

    var strokeCount = 0;
    
    $(function(){
    
        $(".nopaste").bind("copy paste", function(e){
            e.preventDefault();
        });
    
        $("#countstroke").keyup(function(){
            $("#count").text("Count: " + (++strokeCount));
        });
    });​
    

    If you want to take it a step further, you can enforce that only the L and R keys are registered (http://jsfiddle.net/kBJGM/5/):

    $("#restrictivecount").keypress(function(e){
        var seq = rstrokeCount % 2;
        var allow = true;
        switch(e.keyCode){
            case 76:
            case 108: // L or l
                if (seq == 1) allow = false;
            break;
            case 82:
            case 114: // R or r
                if (seq == 0) allow = false;
            break;               
            default:
                allow = false;
            break;               
        }
    
        if (allow)
            $("#rcount").text("Count: " + (++rstrokeCount));
        else
            e.preventDefault();
    });