Search code examples
javascripttimequaltrics

Javascript - register how long user pressed a given button during whole visit


I'm programming an experiment in Qualtrics and I basically need to create, with Javascript, a variable that tells me how long (total) participants held down any button. Pressing a button will display text to the participants and releasing it will make the text disappear, so basically it tells me how much time they had to read the text. So let's say they press the button three times, first for 30 seconds, second for 10 seconds and third for 2 seconds, this code should store the value 42.

What I have so far is this:

addEventListener("keydown", function(event) {
if (event.keyCode == 86)
    document.getElementById("text").innerHTML = "Text to show";
    var d1 = new Date();
    document.getElementById("div1").innerHTML = d1.getTime(); 

});
addEventListener("keyup", function(event) {
if (event.keyCode == 86)
    document.getElementById("text").innerHTML = "";
    var d2 = new Data();
    var d1 = parseFloat(document.getElementById("div1"));
    var diff = d2 - d1.getTime();
    var old = parseFloat(document.getElementById("div2"));
    var old = old + diff;
    document.getElementById("div2").innerHTML = old;        
    Qualtrics.SurveyEngine.setEmbeddedData("readingtime", totalTime);
});

I store the values in divs because I can't seem to reuse values from one event listener to the other (this is probably because I don't know enough about javascript and scopes). Oh, and the last function is just a Qualtrics-specific function to store the value in the database. Anyway, I can't get it to work, when I check the variable in the database it is simply empty. Anyone can spot what I'm doing wrong?


Solution

  • I did a few changes to your code:

    • Added global variables
    • Added few missing brackets
    • Attached listeners to window
    • Removed multiple calls to DOM elements
    • Created a function for each event listener
    • Rounded the elapsed time to seconds

    var d0;
    var d1;
    
    var subtotal = 0;
    var total = 0;
    
    var div1 = document.getElementById("div1");
    var text = document.getElementById("text");
    
    window.addEventListener("keydown", dealWithKeyDown, false);
    window.addEventListener("keyup", dealWithKeyUp, false);
    
    function dealWithKeyDown(event) {
        if (event.keyCode == 86) {
    
            if (typeof d0 === 'undefined') {
                d0 = new Date();
            }
    
            d1 = new Date();        
            subtotal = Math.round((d1.getTime() - d0.getTime()) / 1000);  
    
            div1.innerHTML = subtotal;
            text.innerHTML = "Text to show";
        }
    }
    
    function dealWithKeyUp(event) {
        if (event.keyCode == 86) {
            total = total + subtotal;
            text.innerHTML = "";
            d0 = undefined;       
            Qualtrics.SurveyEngine.setEmbeddedData("readingtime", total);
        }
    }