Overview: Player API
Referencing the player
To use the API functions, you need access to the player object. This is easy to do. You just need to make sure your video tag has an ID. The example embed code has an ID of myPlayerID
, and the player object will be held in the myPlayer
variable. If you have multiple videos on one page, make sure every video tag has a unique ID.
var myPlayer = videojs.getPlayer('myPlayerID');
Player ready method
The time it takes Video.js to set up the video and API will vary depending on multiple factors, such as connection speed. For that reason we want to use the player's ready()
method to trigger any code that requires the player's API.
videojs.getPlayer('myPlayerID').ready(function() {
var myPlayer = this;
// EXAMPLE: Handle an event
myPlayer.on('loadstart',doLoadstart);
});
Player ready vs. video in player ready
From what has been related in this document you might think this is a safe use of the API:
videojs.getPlayer('myPlayerID').ready(function() {
var myPlayer = this;
// Play the video in the player
myPlayer.play()
});
The problem that just because the player is ready for interaction does NOT guarantee the video in the player is loaded and ready to be, in this example, played. For this reason, you will have to use the loadedmetadata
event which guarantees the video is ready to play. The code would appear as follows:
videojs.getPlayer('myPlayerID').ready(function() {
var myPlayer = this;
// Play the video in the player
myPlayer.on('loadedmetadata',function(){
myPlayer.play();
})
});
If calling the play()
method is the only task to perform in the function and you are not going to interact with the player in another way, this code could be simplified to this (no need to use the ready()
method):
videojs.getPlayer('myPlayerID').on('loadedmetadata',function(){
var myPlayer = this;
myPlayer.play();
});
API Methods
Now that you have access to a ready player, you can control the video, get values, or respond to video events. The Video.js API function names follow the HTML5 media API. The main difference is that getter/setter functions are used for video properties.
// setting a property on a bare HTML5 video element
myVideoElement.currentTime = "120";
// setting a property on a Video.js player
myPlayer.currentTime(120);
The full list of player API methods and events can be found in the player API docs.