Custom Javascript code not working when another question is added | XM Community
Skip to main content

I am trying to collect mouse movements in a Qualtrics survey. The problem is, the code works fine when there is only one question measuring the mouse movements but as soon as I add another question in a new block and apply the same code for that question, the results only store data from the second question.
I tried changing the names of the variables for the second question, but it didn't work. How can I apply this code to more than one question and still store data for each question? Any advice/help would be appreciated. Thank you.
Below is the code:

/*Place your JavaScript here to run when the page loads*/
Qualtrics.SurveyEngine.addOnload

(function()
{

/*Hide previous button*/
this.hidePreviousButton();

/*Hide next button and auto-advance on choosing options*/
this.hideNextButton();
this.questionclick = function(event,element)
{
if (element.type == 'radio')
{
this.clickNextButton();
}
}

/*Hide radio buttons*/
jQuery('input[type=radio]').hide();

Qualtrics.SurveyEngine.addOnPageSubmit(function(type)
{
if(type == "next")
{
Qualtrics.SurveyEngine.setEmbeddedData("xPos", delayedXPos.join("a"));
Qualtrics.SurveyEngine.setEmbeddedData("yPos", delayedYPos.join("a"));
Qualtrics.SurveyEngine.setEmbeddedData("time", delayedTime.join("a"));
}
});

});


/*mouse-tracking function*/

document.onmousemove = getMousePosition; //set document to record mouse position

//initialize arrays
var delayedXPos = new Array();
var delayedYPos = new Array();
var delayedTime = new Array();

var xPos = new Array();
var yPos = new Array();

//initialize time variables
var initTime = new Date().getTime();
var timer_is_on=0;
var t;

//time interval for data collection in ms
var dt=10;

//flag signaling whether getMousePosition has been called
mp_called = 0;

//function that determines action when mouse moves
function getMousePosition(mp)
{
var divPos = getPosition(document.getElementById("Questions"));
xPos.push(mp.pageX - divPos[0]);
yPos.push(mp.pageY - divPos[1]);
mp_called = 1;
return true;
}

function timedCount()
{
if(mp_called){
delayedXPos.push(xPos[xPos.length-1]);
delayedYPos.push(yPos[yPos.length-1]);
var timeInSec = (new Date().getTime()-initTime) / 1000.;
delayedTime.push(timeInSec);
}
t=setTimeout("timedCount()",dt);
}

function doTimer()
{
if (!timer_is_on)
{
initTime = new Date().getTime();
timer_is_on=1;
timedCount();
}
}

function getPosition(obj){

var topValue= 0,leftValue= 0;

while(obj)
{
leftValue+= obj.offsetLeft;
topValue+= obj.offsetTop;
obj= obj.offsetParent;
}

return [leftValue, topValue];
}

//start collecting data after page loads
document.onload = doTimer();

Be the first to reply!

Leave a Reply