3

[JavaScript] Show Quiz After End of YouTube Video

 2 years ago
source link: http://siongui.github.io/2017/03/03/javascript-show-quiz-after-youtube-video-end/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Show quiz after the end of YouTube video. The quiz will appear at the end of video. See demo first.

Source Code

HTML: Note that put the HTML code before JavaScript code, otherwise getElementById will return null.

<div id="player"></div>
<div id="quiz" class="invisible">Quiz: What is the name of the video?</div>

CSS: the class .invisible is used to hide the quiz initially. After the end of YouTube video, this class will be removed from the div of quiz.

.invisible { display: none; }
#quiz {color: red; font-size: larger; margin-top: 1.25em;}

JavaScript: Basically the same as the example of YouTube API reference [1], except that check if the video is ended in onPlayerStateChange, and show the quiz if the video is ended.

var quiz = document.getElementById("quiz");

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: 'hS5CfP8n_js',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady(event) {
  event.target.playVideo();
}

function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.ENDED) {
    quiz.classList.remove("invisible");
  }
}

You can force the user to watch the full YouTube video by the trick [2]. But this is not suggested because it is too annoying.


Tested on:

  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK