[JavaScript] Show Quiz After End of YouTube Video


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) {

function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.ENDED) {

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)


[1]YouTube Player API Reference for iframe Embeds | YouTube IFrame Player API | Google Developers
[2]Force a user to watch the whole video - Stack Overflow