Socket
Socket
Sign inDemoInstall

youtube-background

Package Overview
Dependencies
1
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    youtube-background

Simple JS plugin for embedding YouTube, Vimeo and HTML5 videos as a cover background


Version published
Weekly downloads
3.1K
increased by5.85%
Maintainers
1
Install size
2.33 MB
Created
Weekly downloads
 

Readme

Source

📺 youtube-background

npm version CSS gzip size

Another 100 liner in a form of a simple script (or jQuery plugin) to facilitate YouTube embeds as a cover background using YouTube Embed API.

I wrote this code several times over the years and never bothered to make it reusable. Now when I needed it again I could not even find where I wrote it last...

Goodbye careless days... I'm getting old...

DEMO HERE ➡️

Features

  • Play/Pause button
  • Mute/Unmute button
  • Video will pause when not visible
  • No CSS required
  • No longer jQuery dependant

Installation

As a JS module

To install the package from NPM run the good old command

npm install youtube-background

To import it in your script add:

import 'youtube-background';

Don't forget to point your bundler to use node_modules as an include path.

If you wish to use it as a jQuery plugin, make sure you import jQuery as well.

Over CDN

<script type="text/javascript" src="https://unpkg.com/youtube-background/jquery.youtube-background.js"></script>

or minified:

<script type="text/javascript" src="https://unpkg.com/youtube-background/jquery.youtube-background.min.js"></script>

Usage

Usage is pretty simple, add a data attribute data-vbg containing a full YouTube, Vimeo or video file link or just the YouTube or Vimeo ID.

You can trigger all elements containing the noted attribute with $("[data-vbg]").youtube_background();, or specify your selector, on jQuery document ready event.

Note: From version 1.0.6 jQuery is no longer a dependency, but purely optional. To initialise youtube video backgrounds without jQuery use: new VideoBackgrounds('[data-vbg]');.

P.S. https://www.youtube.com/player_api is injected automatically, only once per script init. I've seen some implementations like Elementor WP plugin that inject it several times, for no reason. Anyway, you're welcome.

Quick Example

	<style>
		/* optional css fade in animation */
		iframe {
			transition: opacity 500ms ease-in-out;
			transition-delay: 250ms;
		}
	</style>

	<!-- target element -->
    <div data-vbg="https://www.youtube.com/watch?v=eEpEeyqGlxA"></div>

    <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery('[data-vbg]').youtube_background();
        });
    </script>

Properties

PropertyDefaultAcceptsDescription
play-buttonfalsebooleanAdds a toggle pause button
mute-buttonfalsebooleanAdds a toggle mute button
autoplaytruebooleanAutoplay loaded video
mutedtruebooleanLoad video muted
looptruebooleanLoop loaded video
mobilefalsebooleanKeep the youtube embed on mobile
fit-boxfalsebooleanSet iframe to fit the container, meaning width: 100%; height: 100%
inline-stylestruebooleanEnable/disable inline styles from the iframe and wrapper. The default wrapper styles are: background-size: cover;, background-repeat: no-repeat; and background-position: center;; the default iframe styles are top: 50%;, left: 50%;, transform: translateX(-50%) translateY(-50%);, position: absolute;, and opacity: 0;
load-backgroundfalsebooleanFetch background from youtube or vimeo THIS DEFAULTS TO FALSE since v1.0.18. It is recommended that you provide and host your own background photo preferably as an image element with srcset and loading="lazy" for performance reasons. Works only with YouTube and Vimeo.
posternullstringProvide your own background
offset100intshowinfo:0 id deprecated since September 25, 2018. - this setting makes the video a bit larger than it's viewport to hide the info elements. This setting defaults to 100 only for YouTube videos.
resolution16:9stringdeclare video resolution (work in progress)
pausefalsebooleanAdds a toggle pause button (deprecated)
start-at0intVideo starts playing at desired time in seconds
end-at0intVideo ends playing at desired time in seconds. 0 means it will play to the end.
always-playfalsebooleanVideo will stop playing unless always-play is set to true.
volume1floatFrom 0 to 1. 0 is muted, 1 is full volume. 0.5 is half volume. Sets initial volume. Setting volume doesn't work on mobile, so this setting won't have an effect on mobile.
no-cookietruebooleanDisable cookies. This will prevent YouTube and Vimeo from storing information and tracking you across the web. It is set to true by default.
force-on-low-batteryfalsebooleanWhen mobile device is on battery saver mode, the videos will not autoplay. This setting will force autoplay on battery saver mode on user first interaction. This setting is set to false by default. Be mindful of your users and their data plans, and their battery life.
lazyloadingfalsebooleanLazyload the ifreame/video. This setting is set to false by default. Keep in mind that the script tracks the intersecting videos and pauses them when they are not visible for the reasons of improving the performance. Use lazyloading to minimize the data usage and improve performance even more.

Noted properties can be added as html attributes as:

  • data-vbg-play-button
  • data-vbg-mute-button
  • data-vbg-autoplay
  • data-vbg-mooted
  • data-vbg-loop
  • data-vbg-mobile
  • data-vbg-offset
  • data-vbg-resolution
  • data-vbg-fit-box
  • data-vbg-load-background
  • data-vbg-poster
  • data-vbg-inline-styles
  • data-vbg-start-at
  • data-vbg-end-at
  • data-vbg-always-play
  • data-vbg-volume
  • data-vbg-no-cookie
  • data-vbg-force-on-low-battery
  • data-vbg-lazyloading
Example - Properties as HTML attributes
    <div data-vbg-play-button="true" data-vbg="https://www.youtube.com/watch?v=eEpEeyqGlxA"></div>

    <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery('[data-vbg]').youtube_background();
        });
    </script>
Example - Properties as JSON
    <div data-vbg="https://www.youtube.com/watch?v=eEpEeyqGlxA"></div>

    <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery('[data-vbg]').youtube_background({
      				'play-button': true
      			});
        });
    </script>

Events

  • video-background-ready - when the video is ready to play, this event is triggered. HTML5 videos are ready to play immediately.
  • video-background-time-update - whenever the time of the video changes while video is playing, this event is triggered. The current time is available from the instance variable event.detail.currentTime. On Vimeo and YouTube this event is fired in 250ms intervals.
  • video-background-state-change - video changes state. The state is available from the instance variable event.detail.currentState. It can be: notstarted, ended, playing, paused, buffering, cued.
  • video-background-play - video starts playing
  • video-background-pause - video is paused
  • video-background-ended - video ended event. Keep in mind that if loop is set to true the video will start playing from the start after this event.
  • video-background-mute - video sound is muted
  • video-background-unmute - video sound is unmuted
  • video-background-volume-change - video volume is changed. The volume is available from the instance variable event.detail.volume.

Events bubble. If you go vanilla, you can get the video object via event.detail.

You can add listeners to the events onto the element that you've initialised the video background. If the ID of that element is #video-background, you can add listeners like this:

document.querySelector('#video-background').addEventListener('video-background-ready', function(event) {
    console.log('video-background-ready'); // the video instance object
    console.log(event.detail); // the video instance object
});

or with jQuery:

jQuery('#video-background').on('video-background-ready', function(event) {
    console.log('video-background-ready'); // the video instance object
    console.log(event.originalEvent.detail); // the video instance object
});

Development

Development setup uses POOPS bundler to bundle ES modules into IIFE jquery.youtube-background.js and jquery.youtube-background.min.js

POOPS is a simple bundler + static site builder that I've created, do give it a try and let me know what you think. It's still in early development, but it's already quite useful.

To install the required package for running POOPS, run:

npm install

To run the server on http://localhost:4040, run:

npm run dev

Code will automatically be packaged into IIFE while you develop, and the page will automatically reload on changes.

To just build the code, without running the local server, run:

npm run build

THE END.

Keywords

FAQs

Last updated on 06 Nov 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc