Javascript: track video viewing | XM Community
Skip to main content
I am trying to track if people have watched the video in my Qualtrics survey.

I came out with this Java code but it doesn't seem to be working. Can someone help me please?



Here is the code:

Qualtrics.SurveyEngine.addOnReady(function()

{

var playCounter = 0;

function onFinished(){

playCounter++;

Qualtrics.SurveyEngine.setEmbeddedData("click1", playCounter);

}



$('videoPlayer').addEventListener('ended', onFinished);



});



click1 is my embedded data

video player is my video's ID
In your html, remove the existing player and just add the following:



```html

<div id="player">Loading...</div>

```



Now in your JavaScript:



```javascript

Qualtrics.SurveyEngine.addOnReady(function() {

var videoId = 'EzKImzjwGyM';

var autoplay = true;

var hideControls = true;



function finished() {

// whatever you want to do

console.log('complete');

alert('finished!');

Qualtrics.SurveyEngine.setEmbeddedData('VideoComplete', 'YES');

}

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";

var firstScriptTag = document.getElementsByTagName('script')[0];

firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

if (hideControls) {

hideControls = 0;

} else {

hideControls = 1;

}

var player;



function onYouTubeIframeAPIReady() {

player = new YT.Player('player', {

height: '390',

width: '640',

videoId: videoId,

events: {

'onReady': onPlayerReady,

'onStateChange': onPlayerStateChange

},

playerVars: {

controls: 0

}

});

}



function onPlayerReady(event) {

if (autoplay) {

event.target.playVideo();

}

}

var done = false;



function onPlayerStateChange(event) {

if (event.data == 0) {

finished();

}

}

window.setTimeout(function() {

onYouTubeIframeAPIReady(); // for some reason it doesn't hear this so you have to manually call it

}, 1000);

});



```



Notice that I added some variables at the top there for you to configure. Make sure to add your video ID. You probably should disable skipping in the video. If you want to show controls, you can set `hideControls` = `false`. Additionally, if you don't want to autoplay, set it also to `false`.



Obviously you can change the behavior of what happens in the `finished()` function there at the top. You don't want it `alert()`ing, I'm sure.



Working example: https://qualtricssfi.az1.qualtrics.com/jfe/preview/SV_5axPKjtJ94a9wvr?Q_SurveyVersionID=current&Q_CHL=preview
one solution is autoplay and disable next button for sometime and activate it later.
Thank you so much! (with a lot of delay...)

Leave a Reply