Fullscreen Background Video Using YouTube Player API

Category: Javascript | October 13, 2020
Author:Joe O'Brien
Views Total:3,234 views
Official Page:Go to website
Last Update:October 13, 2020
License:MIT

Preview:

Fullscreen Background Video Using YouTube Player API

Description:

A simple JavaScript solution to use a Youtube video as the fullscreen background for your website using Youtube Player Iframe API.

How to use it:

1. Create a container for the video background and specify the Youtube Video Id in the data-video-id attribute:

<div id="youtubeEmbed" class="bg_video" data-video-id="Tb1lR8Z5oM"></div>

2. Make the video background fullscreen.

.bg_video, iframe {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  width: 100vw;
  height: 56.25vw;
  /* 9/16*100 = 56.25 */
  min-height: 100vh;
  min-width: 177.77vh;
  /* 16/9*100 = 177.77 */
}
iframe {
  opacity: 0;
}
iframe.loaded {
  opacity: 1;
}

3. The JavaScript to load the Youtube Video.

// Get element
var youtubeEmbedElement = document.getElementById("youtubeEmbed");
// Add YouTube API script
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;
var videoId = youtubeEmbedElement.dataset.videoId;
var startSeconds = 184;
var endSeconds = 210;
onYouTubeIframeAPIReady = function () {
  player = new YT.Player("youtubeEmbed", {
    videoId: videoId, // YouTube Video ID
    playerVars: {
      autoplay: 1, // Auto-play the video on load
      autohide: 1, // Hide video controls when playing
      disablekb: 1,
      controls: 0, // Hide pause/play buttons in player
      showinfo: 0, // Hide the video title
      modestbranding: 1, // Hide the Youtube Logo
      loop: 1, // Run the video in a loop
      fs: 0, // Hide the full screen button
      rel: 0,
      enablejsapi: 1,
      start: startSeconds,
      end: endSeconds
    },
    events: {
      onReady: function (e) {
        e.target.mute();
        e.target.playVideo();
      },
      onStateChange: function (e) {
        if (e.data === YT.PlayerState.PLAYING) {
          document.getElementById("youtubeEmbed").classList.add("loaded");
        }
        if (e.data === YT.PlayerState.ENDED) {
          // Loop from starting point
          player.seekTo(startSeconds);
        }
      }
    }
  });
};

You Might Be Interested In:


4 thoughts on “Fullscreen Background Video Using YouTube Player API

    1. BelloTheKid

      It does work! try Adjusting the startSeconds and stopSeconds parameters 😉

      Reply
  1. BelloTheKid

    Yes it does work, try changing the start and stop seconds in the js file if it is not working for you 😉

    Reply

Leave a Reply