Javascript: track video viewing | XM Community
Solved

Javascript: track video viewing

  • 23 July 2018
  • 3 replies
  • 246 views

Userlevel 1
Badge +2
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
icon

Best answer by mattyb513 25 July 2018, 05:40

View original

3 replies

Userlevel 6
Badge +6
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
Userlevel 7
Badge +33
one solution is autoplay and disable next button for sometime and activate it later.
Userlevel 1
Badge +2
Thank you so much! (with a lot of delay...)

Leave a Reply