Code Monkey home page Code Monkey logo

youtube-video-js's Introduction

Build Status npm version

YouTube Video

A <youtube-video> web component that allows you to easily play and control YouTube videos, powered by the YouTube IFrame Player API. In addition to simple rendering, videos can be played, stopped, paused, and more all with simple, native javascript.

This library aims to mimick the methods and properties of HTML5's <video> tag to offer a simple, standardized API that is easy to use and adheres to the latest video tag specifications and supports all major media events.

Installation

npm i youtube-video-js

Then you can use reference before running your build script

import 'youtube-video-js';

Or you can load it using the <script> tag in your html page

<script
    type="module"
    src="/node_modules/youtube-video-js/dist/youtube-video.js"
></script>

Usage

To render a YouTube video, just declare the component in your HTML. Once created (instantiated), the instance can be accessed by JavaScript and will have the same methods that are available on the HTMLMediaElement.

Note: You MUST be requesting a YouTube video from a website that must be either a valid domain or localhost (NOT an IP address) or video wont work! YouTube's requirement, not mine :)

<!-- index.html -->
<script
    type="module"
    src="/node_modules/youtube-video-js/dist/youtube-video.js"
></script>
<youtube-video
    width="640"
    height="360"
    src="https://www.youtube.com/watch?v=Wn9twYUXw6w"
    autoplay
    controls
/>

<script>
    const videoElement = document.querySelector('youtube-video');
    // must wait for DOM to be ready and for component to be accessible
    document.addEventListener('DOMContentLoaded', function () {
        // wait for loading
        videoElement.load().then(() => {
            // pause video after two seconds
            const timer = setTimeout(function () {
                videoElement.pause();
                clearTimeout(timer);
            }, 2000);
        });
    });
</script>

Listen to the video's events

You can also subscribe to MediaEvents just as you would with a native <video> element.

const video = document.querySelector('youtube-video');

video.addEventListener('playing', function () {
    // video has started playing!
});

video.addEventListener('pause', function () {
    // video has been paused!
});

video.addEventListener('ended', function () {
    // video has ended!
});

video.addEventListener('loadstart', function () {
    // play video
    video.play();
    // pause video after four seconds
    const timer = setTimeout(function () {
        video.pause();
        clearTimeout(timer);
    }, 4000);
});

Multiple Videos

When dealing with multiple videos that use this library (multiple videos on a single web page for instance), all other already-playing videos will automatically pause if a video is played. This ensures that no two YouTube videos will ever be playing at the exact same time, ensuring the best possible experience for your users.

const [firstVideoElement, secondVideoElement] = document.querySelectorAll('youtube-video');

firstVideoElement.addEventListener('pause', function () {
    // video has been paused because video2 started playing!
});

// load both videos
Promise.all([firstVideoElement.load(), secondVideoElement.load()]
    .then(() => firstVideoElement.play())
    .then(() => {
       // play video2 to trigger pausing of video1
       secondVideoElement.play();
    });

Extending

You can also extend the youtube video element to create your own custom versions:

import { YoutubeVideoElement } from 'youtube-video-js/dist/youtube-video-element.js';
class CustomYoutubeElement extends YoutubeVideoElement {
    // your custom code here
}
customElements.define('custom-youtube-element', CustomYoutubeElement);

Examples

Code samples can be found in the examples folder. To run them, pull down this project and

npm start

Development

Run tests:

npm install
npm test

youtube-video-js's People

Contributors

data-doge avatar dependabot-preview[bot] avatar dependabot[bot] avatar joshrishell avatar markcellus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

youtube-video-js's Issues

Not working with google analytics

There is a problem with loadYTScript
https://github.com/markcellus/youtube-video-js/blob/master/src/youtube-video.ts#L208
This function expects that window.onYouTubeIframeAPIReady is not touched before. And doesn't handle it.
Looks like google analytics sets this value, which makes this package not working.
https://www.googletagmanager.com/gtag/js?id=G-8P5GQ3C7YC

nit: returning value from Promise is a little bit confusing for read
https://github.com/markcellus/youtube-video-js/blob/master/src/youtube-video.ts#L218

Add a demo page

... that puts videos in full swing (for public and for debugging purposes).

IE 11 not resolving Youtube Video load

Not necessarily a bug with this package but when attempting to load Youtube video API in IE 11, Youtube never fires the onError or even the onReadyState callbacks

when i load page in mobile. video is not autoplay.

message from developed console : Failed to execute 'play' on 'HTMLMediaElement': API can only be initiated by a user gesture.

this is my code:

var videoEl = document.getElementById("slider-bg-video");

var player = new YoutubeVideo({
    el: videoEl,
    customWrapperClass : "video-wrapper flex-video widescreen"
});
videoEl.load().then(function () {
    videoEl.play(); 
});

all same with demo code.

Do people still use this package? :thinking:

Haven't worked on this repo/package for a while since I'm not too sure if people even still need this. Although, I'm curious if it's worthwhile to continue maintaining it.

If you'd like to see this package continue development, please upvote this thread (:+1: ) and if not feel free to downvote (:-1:). And please feel free to leave a comment on your vote if you have something additional to add. Thanks a lot for your support and looking forward to hearing from you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.