youtube-background.js: YouTube, Vimeo & HTML5 Video Background
| File Size: | 225 KB |
|---|---|
| Views Total: | 25221 |
| Last Update: | |
| Publish Date: | |
| Official Website: | Go to website |
| License: | MIT |
youtube-background.js is a JavaScript video background library for YouTube, Vimeo, and self-hosted HTML5 video files.
It turns a normal container into a responsive video background for hero sections, banners, landing pages, and full-page layouts, with playback controls, start and end times, looping, lazy loading, and a common API across supported video sources.
Features
- YouTube, Vimeo, and self-hosted HTML5 video backgrounds.
- Responsive sizing that fills the video container.
- Autoplay, mute, loop, start time, end time, and volume controls.
- Optional play and mute buttons.
- Intersection-based playback state management for off-screen videos.
- Optional lazy loading for YouTube and Vimeo iframes.
- API methods for playback, seeking, source changes, and lifecycle control.
- Custom events for playback, state, volume, resize, seeking, and teardown.
How To Use youtube-background.js
1. Install The Library
Load the standalone bundle from a CDN.
<script src="https://unpkg.com/youtube-background/dist/youtube-background.min.js"></script> <!-- OPTIONAL Stylesheet --> <link rel="stylesheet" href="https://unpkg.com/youtube-background/dist/youtube-background-controls.min.css">
Or install the package with NPM and import the VideoBackgrounds class.
npm install youtube-background
import { VideoBackgrounds } from 'youtube-background';
2. Create A YouTube Video Background
Set the video URL in data-vbg. The container can be a hero, banner, section, or other block that needs a video background.
<section
id="hero-video"
data-vbg="https://www.youtube.com/watch?v=eEpEeyqGlxA">
<div class="hero-content">
<h2>Product Launch</h2>
</div>
</section>
Initialize every matching element with the standalone browser build.
var videoBackgrounds = new VideoBackgrounds('[data-vbg]');
3. Use Vimeo Or HTML5 Video Files
The same data-vbg attribute accepts Vimeo links and supported video file URLs.
<div data-vbg="https://vimeo.com/76979871"></div> <div data-vbg="/media/landing-page.mp4"></div>
var videoBackgrounds = new VideoBackgrounds('[data-vbg]');
4. Configure A Video Background
Pass an options object as the second constructor argument. This example starts the video at 8 seconds, loops it, loads it muted, and adds a play button.
var videoBackgrounds = new VideoBackgrounds('#hero-video', {
'start-at': 8,
'loop': true,
'muted': true,
'play-button': true
});
5. Configure It With Data Attributes
HTML attributes override matching values passed during initialization.
<div data-vbg="https://www.youtube.com/watch?v=eEpEeyqGlxA" data-vbg-start-at="8" data-vbg-end-at="28" data-vbg-loop="true" data-vbg-muted="true" data-vbg-play-button="true"> </div>
var videoBackgrounds = new VideoBackgrounds('[data-vbg]');
Options
Playback Options
| Option | Description |
|---|---|
autoplay |
Boolean. Default: true. Starts playback after the player is ready. |
muted |
Boolean. Default: true. Starts the video muted. |
loop |
Boolean. Default: true. Restarts the video after it reaches the configured end point. |
start-at |
Integer. Default: 0. Sets the playback start time in seconds. |
end-at |
Integer. Default: 0. Sets the playback end time in seconds. A value of 0 uses the full video duration. |
always-play |
Boolean. Default: false. Keeps playback active when normal visibility-based pausing would stop the video. |
volume |
Float. Default: 1. Sets the initial volume from 0 to 1. Mobile platforms do not apply this setting. |
play-button |
Boolean. Default: false. Adds the built-in play and pause button. |
mute-button |
Boolean. Default: false. Adds the built-in mute and unmute button. |
pause |
Boolean. Default: false. Deprecated option for the older pause button behavior. |
Layout And Loading Options
| Option | Description |
|---|---|
mobile |
Boolean. Default: true. Keeps the video embed active on mobile devices. Set it to false to skip mobile initialization. |
fit-box |
Boolean. Default: false. Sets the player iframe to width: 100% and height: 100%. |
inline-styles |
Boolean. Default: true. Applies the library's positioning and background styles to the wrapper and player. |
load-background |
Boolean. Default: false. Fetches a background image for YouTube or Vimeo before player playback. |
poster |
String or null. Default: null. Sets a custom poster or background image. |
offset |
Integer. Default: 100 for YouTube. Enlarges the video beyond its container edges. |
resolution |
String. Default: 16:9. Sets the expected video aspect ratio. |
lazyloading |
Boolean. Default: false. Adds lazy loading to YouTube and Vimeo iframes. It does not apply to HTML5 <video> elements. |
Privacy, Mobile, And Accessibility Options
| Option | Description |
|---|---|
no-cookie |
Boolean. Default: true. Uses privacy-oriented YouTube and Vimeo embeds that disable their normal cookie behavior. |
force-on-low-battery |
Boolean. Default: false. Tries to start autoplay after the first user interaction when battery saver mode blocks automatic playback. |
title |
String, false, or null. Default: Video background. Sets the player title. A false or null value removes the title attribute. |
HTML Data Attributes
Each public initialization option can use a data-vbg-* attribute where supported. The source URL belongs in data-vbg.
data-vbg-play-buttondata-vbg-mute-buttondata-vbg-autoplaydata-vbg-muteddata-vbg-loopdata-vbg-mobiledata-vbg-offsetdata-vbg-resolutiondata-vbg-fit-boxdata-vbg-load-backgrounddata-vbg-posterdata-vbg-inline-stylesdata-vbg-start-atdata-vbg-end-atdata-vbg-always-playdata-vbg-volumedata-vbg-no-cookiedata-vbg-force-on-low-batterydata-vbg-lazyloadingdata-vbg-title
The legacy data-ytbg-* prefix is also recognized. When both prefixes exist on the same element, data-vbg-* takes precedence. Source URLs can use data-vbg, data-youtube, or data-ytbg, in that priority order.
Instance Methods
Playback And Seeking Methods
| Method | Description |
|---|---|
play() |
Starts video playback. |
pause() |
Pauses playback and records the user-paused state. |
mute() |
Mutes the current video. |
unmute() |
Restores audio for the current video. |
setVolume(value) |
Sets volume from 0 to 1. |
getVolume() |
Returns the current volume. Vimeo returns a Promise that resolves to the volume value. |
seek(percent) |
Moves playback to a percentage from 0 to 100. |
seekTo(seconds) |
Moves playback to a specific time in seconds. |
Source And Lifecycle Methods
| Method | Description |
|---|---|
setSource(url) |
Changes the source to another URL of the same provider type as the current instance. |
setStartAt(seconds) |
Changes the configured playback start time. |
setEndAt(seconds) |
Changes the configured playback end time. |
softPlay() |
Starts playback while preserving the hard paused flag used for user-initiated pauses. |
softPause() |
Pauses playback while preserving the hard paused flag. |
destroy() |
Removes this video background instance and restores its element to its pre-initialization state. |
Get An Instance And Control It
var element = document.querySelector('#hero-video');
var instance = videoBackgrounds.get(element);
instance.pause();
instance.seekTo(12);
instance.setVolume(0.5);
instance.play();
Factory Methods
| Method | Description |
|---|---|
add(element, options) |
Initializes a new video background on an element. The options argument is optional. |
get(elementOrUid) |
Returns a video background instance by DOM element or generated UID. |
destroy(elementOrInstance) |
Destroys one instance and restores its element. |
destroyAll() |
Destroys all indexed video background instances but keeps the factory listeners active. |
disconnect() |
Destroys all instances, disconnects observers, and removes global listeners registered by the factory. |
pauseAll() |
Pauses all indexed video backgrounds. |
playAll() |
Starts all indexed video backgrounds. |
muteAll() |
Mutes all indexed video backgrounds. |
unmuteAll() |
Unmutes all indexed video backgrounds. |
setVolumeAll(value) |
Sets volume from 0 to 1 for all indexed instances. |
Instance And Factory Properties
Video Instance Properties
| Property | Description |
|---|---|
paused |
Boolean state set by a direct pause() call. |
muted |
Boolean mute state. |
isIntersecting |
Boolean that reports if the video intersects the viewport. |
currentState |
Current state: notstarted, ended, playing, paused, or buffering. |
currentTime |
Current playback time in seconds. |
percentComplete |
Playback progress as a percentage. |
element |
The DOM element that owns the video background. |
playerElement |
The generated iframe or HTML5 video element. |
player |
The provider player object or HTML5 video element. |
type |
Source type: youtube, vimeo, or video. |
volume |
Current volume from 0 to 1. |
Factory Properties
| Property | Description |
|---|---|
index |
Object that stores initialized video background instances by generated UID. |
intersectionObserver |
The factory's IntersectionObserver instance. |
resizeObserver |
The factory's ResizeObserver instance. The library falls back to the window resize event when needed. |
Events
Playback And Lifecycle Events
| Event | Fires When |
|---|---|
video-background-ready |
The player is ready. HTML5 video backgrounds become ready immediately. |
video-background-time-update |
Playback time changes. YouTube and Vimeo report this event at roughly 250 ms intervals. |
video-background-state-change |
The player changes between notstarted, ended, playing, paused, or buffering. |
video-background-play |
Playback starts. |
video-background-pause |
Playback pauses. |
video-background-ended |
The configured playback range reaches its end. |
video-background-seeked |
A seek operation completes through seek(), seekTo(), or a seek control. |
Audio, Resize, And Teardown Events
| Event | Fires When |
|---|---|
video-background-mute |
The video becomes muted. |
video-background-unmute |
The video becomes unmuted. |
video-background-volume-change |
Volume changes. Read the new value from event.detail.volume. |
video-background-resize |
The video background is resized. |
video-background-destroyed |
An instance is destroyed and its element is restored. |
Listen For A Video Event
var hero = document.querySelector('#hero-video');
hero.addEventListener('video-background-ready', function(event) {
var instance = event.detail;
console.log(instance.currentState);
});
Optional Controls And Video Groups
The optional youtube-background-experimental.min.js bundle contains SeekBar, PlayToggle, MuteToggle, VideoBackgroundGroup, and VideoBackgroundGroups.
<script src="https://unpkg.com/youtube-background/youtube-background-experimental.min.js"></script>
| Control | API |
|---|---|
SeekBar |
Connects a range input to video progress and seeking. Call destroy() to remove its listeners. |
PlayToggle |
Connects a button to play and pause behavior. Call destroy() to remove its listeners. |
MuteToggle |
Connects a button to mute and unmute behavior. Call destroy() to remove its listeners. |
VideoBackgroundGroup |
Controls a sequence with next(), prev(), play(), pause(), mute(), unmute(), and destroy(). |
VideoBackgroundGroups |
Manages multiple groups with add(), get(), destroy(), and destroyAll(). |
Video Group Events
video-background-group-playvideo-background-group-pausevideo-background-group-mutevideo-background-group-unmutevideo-background-group-nextvideo-background-group-previousvideo-background-group-forward-rewindvideo-background-group-backward-rewind
Alternatives And Related Resources
- 10 Best Video Background Plugins In JavaScript: Compare jQuery and vanilla JavaScript background video libraries.
- YTPlayer: A jQuery-focused YouTube background player with playlists and a larger playback API.
- vidim: A vanilla JavaScript alternative for self-hosted and YouTube background videos.
FAQs
Q: Does youtube-background.js require jQuery?
A: No. Initialize VideoBackgrounds directly in new projects. The jQuery wrapper remains available for legacy 1.x integrations.
Q: Can it use Vimeo and local HTML5 video files?
A: Yes. data-vbg accepts supported YouTube links, Vimeo links, and video file URLs. The library creates the matching player type for each source.
Q: Why does my background video not autoplay?
A: Browser autoplay policies commonly block video that starts with sound. Keep muted: true for autoplay backgrounds and confirm that the device is not applying battery-saving playback restrictions.
Q: How do I disable video backgrounds on mobile?
A: Set mobile: false. The default is true, which keeps video backgrounds active on mobile devices.
Q: Can I remove YouTube's large play or pause icon from the embedded video?
A: Page CSS cannot style the contents of the cross-origin YouTube iframe. Treat that bezel as part of the YouTube embed when playback state changes.
Changelog
v2.0.0 (2026-08-31)
- Removed jQuery.
v1.2.0 (2026-08-29)
- Deprecated the jQuery wrapper ahead of its planned removal in 2.0.0.
- Added
VideoBackgrounds.disconnect()for full factory teardown. - Added package exports for direct
VideoBackgroundsESM imports. - Added cleanup methods for optional controls and corrected group event behavior.
- Corrected autoplay, pause persistence, source handling, documentation, and video file detection issues.
v1.1.8 (2024-05-27)
- Added
.m4v,.mov, and.qtMIME mappings. - Updated button ARIA state handling.
v1.0.20 (2023-11-02)
- Added regular HTML5 video file support.
v1.0.18 (2023-10-26)
- Added initial volume control and the global
VIDEO_BACKGROUNDSreference for jQuery usage. - Changed
load-backgroundtofalseby default. - Added the
no-cookieoption with a default value oftrue.
This awesome jQuery plugin is developed by stamat. For more Advanced Usages, please check the demo page or visit the official website.











