A lightweight video player that allows you to easily play and control YouTube videos using the HTML5
<video>
tag and the HTML5
YouTube IFrame Player API. Videos can be played, stopped,
paused, and more all with simple html markup or with 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. It also supports all major
Video events.
You can quickly start using the YouTube Video class as a standalone package, by using one of the pre-built javascript files. Alternatively, you can also use the source files directly if you are running your own build processes.
Suppose you have the following HTML in the DOM for a YouTube video.
<video width="640" height="360">
<source type="video/youtube" src="http://www.youtube.com/watch?v=ye82js0sL32" />
</video>
To start controlling the video with javascript all you need is to pass the <video>
element into the Youtube Video class.
Once created (instantiated), the instance exposes the same methods that are available on the new
HTML5 <video>
element.
This example assumes you already have the Video class loaded as a dependency assigned to a YoutubeVideo
variable.
// start a youtube video
var video = new YoutubeVideo({
el: document.getElementsByTagName('video')[0]
})
video.load().then(() => {
video.play();
video.pause();
});
You can also subscribe to MediaEvents just as
you would with a <video>
element.
let videoElement = document.getElementsByTagName('video')[0];
let player = new YoutubeVideo({
el: document.getElementsByTagName('video')[0]
})
videoElement.addEventListener('loadstart', function () {
// video has started loading!
});
videoElement.load();
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.
let firstVideoElement = document.getElementsByTagName('video')[0];
let firstVideoPlayer = new YoutubeVideo({el: firstVideoElement})
let secondVideoElement = document.getElementsByTagName('video')[1];
let secondVideoPlayer = new YoutubeVideo({el: secondVideoElement})
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();
});
More code samples can be viewed in the examples folder.
Run tests:
npm install
npm test