Categories
Web Development

How to Control a Youtube Video with javascript

Last Tested: 11/21/2020

Sometimes a web developer needs to perform this very important control/monitoring functionality. Whether you need to play a video, see if a video has been watched in its entirety or just integrate the embedded youtube video’s functionality into your code for another reason, it can all be done using the youtube API.

The first important (albeit basic) part of using the Youtube API for these functions is that although the video on your page will look like an embed, you are actually putting an empty div on your page with HTML and the Javascript calls the API and replaces that div with the video you specify.

  1. Put the following in the code of your HTML page:
<div id="video-placeholder"></div>

2. Include a javascript file with the following content (but change videoId to the ID of your video):

var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('video-placeholder', {
        width: 600,
        height: 400,
        videoId: 'Xa0Q0J5tOP0',
        playerVars: {
            color: 'white',
            playlist: 'taJ60kskkns,FG0fTKAqZ5g'
        },
        events: {
            onReady: initialize
        }
    });
}

function initialize(){

    // Update the controls on load
    updateTimerDisplay();
    updateProgressBar();

    // Clear any old interval.
    clearInterval(time_update_interval);

    // Start interval to update elapsed time display and
    // the elapsed part of the progress bar every second.
    time_update_interval = setInterval(function () {
        updateTimerDisplay();
        updateProgressBar();
    }, 1000)

}

3. Include this code in your html page to get the current duration of the video automatically updated:

// This function is called by initialize()
function updateTimerDisplay(){
    // Update current time text display.
    $('#current-time').text(formatTime( player.getCurrentTime() ));
    $('#duration').text(formatTime( player.getDuration() ));
}

function formatTime(time){
    time = Math.round(time);

    var minutes = Math.floor(time / 60),
    seconds = time - minutes * 60;

    seconds = seconds < 10 ? '0' + seconds : seconds;

    return minutes + ":" + seconds;
}

4. Include this code in your HTML page to add a play button for the video:

$('#play').on('click', function () {

    player.playVideo();

});

5. Include this code in your HTML page to add a pause button for the video:

$('#pause').on('click', function () {

    player.pauseVideo();

});

Disclaimer: I do not work for youtube and so had no involvement whatsoever in the creation of Youtube or it’s excellent API. For more information about using the youtube embed API visit the site listed in my sources for a more in-depth explanation.

Source(s):

  1. https://tutorialzine.com/2015/08/how-to-control-youtubes-video-player-with-javascript

Leave a Reply