Embed YouTube Video as Background with jQuery

A lightweight and simple jQuery plugin for embedding YouTube video as a cover background. The plugin uses YouTube video embedding API to fetch video and play it as a webpage (or specific div) background. You just need to add a video URL to HTML5 data attribute then this plugin will automatically set that video as background.

You can add video with any size & duration, it will resized to available screen size. The background video will playing with loop.

Plugin Overview

Plugin: YouTube Background
Author: Nikola Stamatovic
Licence: MIT Licence
Published: August 14, 2019
Repository: Fork on GitHub
Dependencies: jQuery 1.11.3 or Latest version
File Type: zip archive (HTML & JavaScript )
Package Size: 4.86 KB

How to Use Plugin to Embed YouTube Video as Background

1. Load jQuery and YouTube Background plugin’s JavaScript file into your HTML document.

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<!-- YT Video Background JS -->
<script type="text/javascript" src="js/jquery.youtube-background.js"></script>

2. Create a div element with data-youtube attribute that will be used as video background.

<div id="ytbg" data-youtube="https://www.youtube.com/watch?v=eEpEeyqGlxA"></div>

3. The following is complete HTML structure with (container, div wrappers and) some example contents.

<div class="container">
   <main>
      <div class="example-marquee">
         <div id="ytbg" data-youtube="https://www.youtube.com/watch?v=eEpEeyqGlxA"></div>
         <div class="content">
            <div class="inner">
               <h1>Cake in a frying pan? Impossible!</h1>
            </div>
         </div>
      </div>
   </main>
</div>

4. Some CSS to style/adjust the elements.

.example-marquee {
	position: relative;
}

.content {
	display: table;
	width: 100%;
	min-height: 100vh;
	z-index: 1;
	position: relative;
}

.content .inner {
	display: table-cell;
	vertical-align: middle;
	text-align: center;
	padding-left: 16px;
	padding-right: 16px;
}

.content .inner h1 {
	font-size: 62px;
	color: white;
	text-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5);
}

5. Finally, initialize the plugin in jQuery document ready function to active YouTube video background.

jQuery(document).ready(function () {
	$('[data-youtube]').youtube_background();
});