JavaScript

How to Play YouTube Videos as Page Background【YouTube API】

Playing YouTube videos as the background of a web page is an attractive method that provides a strong visual impact.
In this article, I will explain in detail how to embed a video as a background using the YouTube API.
I will introduce specific code examples using HTML, CSS, and JavaScript, making it easy to understand even for beginner engineers.

What you need to prepare

Before starting this project, please prepare the following:

  • Basic knowledge of HTML, CSS, and JavaScript
  • The latest browser (such as Google Chrome or Firefox)
  • Internet connection (to use the YouTube API)

Now, let’s move on to the actual implementation.

CSS code to play YouTube video as page background

First, set up the styles to display the YouTube video as a background. Below is an example of CSS code.
This CSS specifies the background size and position to display the video across the entire screen.
The following CSS applies to the YouTube display area (#youtube-area), the loading area (#loading), and the header area (#header) background with a loading image (loading.jpg).

<style>
* {
  padding: 0;
  margin: 0;
}
body {
  font-size: 14px;
  text-align: center;
  line-height: 2em;
}
#header{
  position: relative;
    height: 100vh;
    text-align: center;
    color: #fff;
    background: url("loading.jpg") no-repeat;
    background-size: cover;
}
#loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-weight: bold;
  font-size: 30px;
}
#loading.disappear{
  display: none;   
}
/* YouTube display area */
#youtube-area{
  position: absolute;
  z-index: 1;
  top: 0;
  right:0;
  left:0;
  bottom:0;
  overflow: hidden;
  opacity: 0;    
}
#youtube-area.appear {
  animation-name:pageanimetuika;
  animation-duration:.6s;
  animation-fill-mode:forwards;
}
@keyframes pageanimetuika{
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
#youtube {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 178vh;
  height: 56vw;
  min-height: 100%;
  min-width: 100%;
}
/* YouTube click-preventing mask area */
#youtube-mask{
    position: absolute;
    z-index: 2;
    top:0;
    width:100%;
    height: 100%;
}
h1{
  position:absolute;
  z-index: 2;
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
  color:#000;
  text-align: center;
  font-size: 30px;
}
.honbun{
  font-size: 30px;
  padding: 100px 0;
}
</style>

HTML code to play YouTube video as page background

Next, let’s look at the HTML example.
Prepare the YouTube display area (id="youtube-area") and the loading display area (id="loading") to show the YouTube video as a background.

<header id="header">
  <div id="loading">Loading…</div>

  <div id="youtube-area">
    <h1>Playing YouTube video as background</h1>
    <div id="youtube"></div><!--YouTube display area-->
    <div id="youtube-mask"></div><!--YouTube click-preventing mask area-->
  </div>
</header>
  
<div class="honbun">
  Insert content from here onwards.
</div>

JavaScript code using YouTube API to play YouTube video as background

First, load the jquery-3.4.1.min.js file.
Here is the JavaScript code that uses the YouTube API to control the background video.
By also using jQuery, you can handle switching the loading screen and set up the initial video configuration.
Write something like YT.Player('ID of the tag where you want to display the YouTube video', {options}).
In the options, configure YouTube API settings such as autoplay and player controls for playing the video.

<script src="jquery-3.4.1.min.js"></script>
<script>
// Loading screen
$(window).on('load',function(){    
        $("#youtube-area").addClass('appear');
        $("#loading").addClass('disappear');
});

// YouTube API
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 ytPlayer;
function onYouTubeIframeAPIReady() {
    ytPlayer = new YT.Player('youtube', {// specify the tag ID where you want to display the video
        videoId: 'P7Od94ikeoI',// specify the video address
        playerVars: {
            playsinline: 1,// play inline
            autoplay:1,// autoplay
            fs:0,// do not show fullscreen button    
            rel: 0,// show related videos from the same channel
            controls: 0,// do not show player controls
            modestbranding: 1, // hide YouTube logo
            iv_load_policy: 3, // hide annotations
            start:30,
        },    
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

// Mute and play
function onPlayerReady(event) {
  event.target.mute();
  event.target.playVideo();
}

// YouTube loop setting
function onPlayerStateChange(event) {
 if (event.data == YT.PlayerState.ENDED) {
    event.target.playVideo();
  }
}
</script>

Demo page: Play YouTube video as background

Please take a look at the demo page created based on the code introduced in this article.
Click the link below to check out the actual working page.

Demo page: Play YouTube video as background

* For the first few seconds, the video title will appear at the top left and the YouTube logo at the bottom right. I wanted to hide these too, but couldn’t find a way.

Conclusion

In this article, I explained how to play YouTube videos as the background of a web page using the YouTube API.
Use this as a reference to add your own styles and settings to create a more attractive web page.
The content is structured to be easy to understand, even for beginners, so please give it a try.

* Please reuse at your own risk.
Do not reuse the Google Analytics tag inside the head tag of the demo page.