Back to Video Js

videojs

docs/legacy-docs/api/video.html

8.23.832.5 KB
Original Source

This documentation is for an outdated version of Video.js. See documentation for the current release.

API Index

videojs Methods

Class Methods

Inherited Methods from Component

videojs

Doubles as the main function for users to create a player instance and also the main library object. The videojs function can be used to initialize or retrieve a player.

var myPlayer = videojs('my_video_id');

DEFINED IN: video.js line number: 40

EXTENDS: component.js

Methods

addClass( element, classToAdd )

Add a CSS class name to an element

Parameters

nameTypeRequiredDescription
elementElementyesElement to add class name to
classToAddStringyesClassname to add

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 586

[back to top]

addLanguage( code, data )

Adding languages so that they're available to all players.

videojs.addLanguage('es', { 'Hello': 'Hola' });

Parameters

nameTypeRequiredDescription
codeStringyesThe language code or dictionary property
dataObjectyesThe data values to be translated

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 403

[back to top]

appendContent( el, content )

Normalizes and appends content to an element.

The content for an element can be passed in multiple types and combinations, whose behavior is as follows:

  • String Normalized into a text node.

  • Element, TextNode Passed through.

  • Array A one-dimensional array of strings, elements, nodes, or functions (which return single strings, elements, or nodes).

  • Function If the sole argument, is expected to produce a string, element, node, or array.

Parameters

nameTypeRequiredDescription
elElement
contentStringElementTextNode

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 648

[back to top]

createEl( [tagName], [properties], [attributes] )

Creates an element and applies properties.

Parameters

nameTypeRequiredDescription
tagNameStringnoName of tag to be created.
propertiesObjectnoElement properties to be applied.
attributesObjectnoElement attributes to be applied.

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 566

[back to top]

createTimeRange( start, end )

Creates an emulated TimeRange object.

Parameters

nameTypeRequiredDescription
startNumberArrayyes
endNumberyesEnd time in seconds

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 427

[back to top]

emptyEl( el )

Empties the contents of an element.

Parameters

nameTypeRequiredDescription
elElement

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 639

[back to top]

extend( The, An )

Subclass an existing class Mimics ES6 subclassing with the extend keyword

// Create a basic javascript 'class'
    function MyClass(name){
      // Set a property at initialization
      this.myName = name;
    }
    // Create an instance method
    MyClass.prototype.sayMyName = function(){
      alert(this.myName);
    };
    // Subclass the exisitng class and change the name
    // when initializing
    var MySubClass = videojs.extend(MyClass, {
      constructor: function(name) {
        // Call the super class constructor for the subclass
        MyClass.call(this, name)
      }
    });
    // Create an instance of the new sub class
    var myInstance = new MySubClass('John');
    myInstance.sayMyName(); // -> should alert "John"

Parameters

nameTypeRequiredDescription
ThefunctionyesClass to subclass
AnObjectyesobject including instace methods for the new class Optionally including a constructor function

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 269

[back to top]

formatTime( seconds, guide )

Format seconds as a time string, H:MM:SS or M:SS Supplying a guide (in seconds) will force a number of leading zeros to cover the length of the guide

Parameters

nameTypeRequiredDescription
secondsNumberyesNumber of seconds to be turned into a string
guideNumberyesNumber (in seconds) to model the string after

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 437

[back to top]

getAttributes( tag )

Get an element's attribute values, as defined on the HTML tag Attributes are not the same as properties. They're defined on the tag or with setAttribute (which shouldn't be used with HTML) This will return true or false for boolean attributes.

Parameters

nameTypeRequiredDescription
tagElementyesElement from which to get tag attributes

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 627

[back to top]

getComponent()

Get a component class object by name

var VjsButton = videojs.getComponent('Button');
    // Create a new instance of the component
    var myButton = new VjsButton(myPlayer);

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 166

[back to top]

getPlayers()

Get an object with the currently created players, keyed by player ID

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 143

[back to top]

hasClass( element, classToCheck )

Check if an element has a CSS class

Parameters

nameTypeRequiredDescription
elementElementyesElement to check
classToCheckStringyesClassname to check

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 577

[back to top]

insertContent( el, content )

Normalizes and inserts content into an element; this is identical to appendContent(), except it empties the element first.

The content for an element can be passed in multiple types and combinations, whose behavior is as follows:

  • String Normalized into a text node.

  • Element, TextNode Passed through.

  • Array A one-dimensional array of strings, elements, nodes, or functions (which return single strings, elements, or nodes).

  • Function If the sole argument, is expected to produce a string, element, node, or array.

Parameters

nameTypeRequiredDescription
elElement
contentStringElementTextNode

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 675

[back to top]

isCrossOrigin( url )

Returns whether the url passed is a cross domain request or not.

Parameters

nameTypeRequiredDescription
urlStringyesThe url to check

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 458

[back to top]

isEl( value )

Determines, via duck typing, whether or not a value is a DOM element.

Parameters

nameTypeRequiredDescription
valueMixed

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 548

[back to top]

isTextNode( value )

Determines, via duck typing, whether or not a value is a text node.

Parameters

nameTypeRequiredDescription
valueMixed

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 557

[back to top]

mergeOptions( defaults, overrides, etc )

Merge two options objects recursively Performs a deep merge like lodash.merge but only merges plain objects (not arrays, elements, anything else) Other values will be copied directly from the second object.

var defaultOptions = {
      foo: true,
      bar: {
        a: true,
        b: [1,2,3]
      }
    };
    var newOptions = {
      foo: false,
      bar: {
        b: [4,5,6]
      }
    };
    var result = videojs.mergeOptions(defaultOptions, newOptions);
    // result.foo = false;
    // result.bar.a = true;
    // result.bar.b = [4,5,6];

Parameters

nameTypeRequiredDescription
defaultsObjectyesThe options object whose values will be overriden
overridesObjectyesThe options object with values to override the first
etcObjectyesAny number of additional options objects

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 304

[back to top]

off( elem, type, fn )

Removes event listeners from an element

Parameters

nameTypeRequiredDescription
elemElementObjectyes
typeStringArrayyes
fnfunctionyesSpecific listener to remove. Don't include to remove listeners for an event type.

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 497

[back to top]

on( elem, type, fn )

Add an event listener to element It stores the handler function in a separate cache object and adds a generic handler to the element's event, along with a unique id (guid) to the element.

Parameters

nameTypeRequiredDescription
elemElementObjectyes
typeStringArrayyes
fnfunctionyesEvent listener.

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 474

[back to top]

one( elem, type, fn )

Trigger a listener only once for an event

Parameters

nameTypeRequiredDescription
elemElementObjectyes
typeStringArrayyes
fnfunctionyesEvent handler function

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 487

[back to top]

parseUrl( url )

Resolve and parse the elements of a URL

Parameters

nameTypeRequiredDescription
urlStringyesThe url to parse

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 449

[back to top]

plugin( name, fn )

Create a Video.js player plugin Plugins are only initialized when options for the plugin are included in the player options, or the plugin function on the player instance is called. See the plugin guide in the docs for a more detailed example

// Make a plugin that alerts when the player plays
    videojs.plugin('myPlugin', function(myPluginOptions) {
      myPluginOptions = myPluginOptions || {};

      var player = this;
      var alertText = myPluginOptions.text || 'Player is playing!'

      player.on('play', function(){
        alert(alertText);
      });
    });
    // USAGE EXAMPLES
    // EXAMPLE 1: New player with plugin options, call plugin immediately
    var player1 = videojs('idOne', {
      myPlugin: {
        text: 'Custom text!'
      }
    });
    // Click play
    // --> Should alert 'Custom text!'
    // EXAMPLE 3: New player, initialize plugin later
    var player3 = videojs('idThree');
    // Click play
    // --> NO ALERT
    // Click pause
    // Initialize plugin using the plugin function on the player instance
    player3.myPlugin({
      text: 'Plugin added later!'
    });
    // Click play
    // --> Should alert 'Plugin added later!'

Parameters

nameTypeRequiredDescription
nameStringyesThe plugin name
fnfunctionyesThe plugin function that will be called with options

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 356

[back to top]

registerComponent( The, The )

Register a component so it can referred to by name Used when adding to other components, either through addChild component.addChild('myComponent') or through default children options { children: ['myComponent'] }.

// Get a component to subclass
    var VjsButton = videojs.getComponent('Button');
    // Subclass the component (see 'extend' doc for more info)
    var MySpecialButton = videojs.extend(VjsButton, {});
    // Register the new component
    VjsButton.registerComponent('MySepcialButton', MySepcialButton);
    // (optionally) add the new component as a default player child
    myPlayer.addChild('MySepcialButton');

NOTE: You could also just initialize the component before adding. component.addChild(new MyComponent());

Parameters

nameTypeRequiredDescription
TheStringyesclass name of the component
TheComponentyescomponent class

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 180

[back to top]

registerTech( The, The )

Register a Tech so it can referred to by name. This is used in the tech order for the player.

// get the Html5 Tech
    var Html5 = videojs.getTech('Html5');
    var MyTech = videojs.extend(Html5, {});
    // Register the new Tech
    VjsButton.registerTech('Tech', MyTech);
    var player = videojs('myplayer', {
      techOrder: ['myTech', 'html5']
    });

Parameters

nameTypeRequiredDescription
TheStringyesclass name of the tech
TheTechyestech class

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 228

[back to top]

removeClass( element, classToRemove )

Remove a CSS class name from an element

Parameters

nameTypeRequiredDescription
elementElementyesElement to remove from class name
classToRemoveStringyesClassname to remove

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 595

[back to top]

setAttributes( el, [attributes] )

Apply attributes to an HTML element.

Parameters

nameTypeRequiredDescription
elElementyesTarget element.
attributesObjectnoElement attributes to be applied.

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 618

[back to top]

toggleElClass( element, classToToggle, [predicate] )

Adds or removes a CSS class name on an element depending on an optional condition or the presence/absence of the class name.

Parameters

nameTypeRequiredDescription
elementElement
classToToggleString
predicateBooleanfunctionno

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 604

[back to top]

trigger( elem, event, [hash] )

Trigger an event for an element

Parameters

nameTypeRequiredDescription
elemElementObjectyes
eventEventObjectString
hashObjectnodata hash to pass along with the event

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 507

[back to top]

videojs( id, [options], [ready] )

Doubles as the main function for users to create a player instance and also the main library object. The videojs function can be used to initialize or retrieve a player.

var myPlayer = videojs('my_video_id');

Parameters

nameTypeRequiredDescription
idStringElementyes
optionsObjectnoOptional options object for config/settings
readyfunctionnoOptional ready callback

Defined in https://github.com/videojs/video.js/blob/master/src/js/video.js line number: 40

[back to top]

$( selector, [context] )

Finds a single DOM element matching selector within the component's contentEl or another custom context.

Parameters

nameTypeRequiredDescription
selectorStringyesA valid CSS selector, which will be passed to querySelector.
contextElementStringno

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 841

[back to top]

$$( selector, [context] )

Finds a all DOM elements matching selector within the component's contentEl or another custom context.

Parameters

nameTypeRequiredDescription
selectorStringyesA valid CSS selector, which will be passed to querySelectorAll.
contextElementStringno

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 861

[back to top]

addChild( child, [options] )

Adds a child component inside this component

myComponent.el();
    // -> 
    myComponent.children();
    // [empty array]

    var myButton = myComponent.addChild('MyButton');
    // -> 
myButton
    // -> myButton === myComponent.children()[0];Pass in options for child constructors and options for children of the child
    var myButton = myComponent.addChild('MyButton', {
      text: 'Press Me',
      buttonChildExample: {
        buttonChildOption: true
      }
    });

Parameters

name
Type
Required
Description

child
String|Component
yes
The class name or instance of a child to add

options
Object
no
Options, including options to be passed to children of the child.

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 315
[back to top]

buildCSSClass()
Allows sub components to stack CSS class names
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 593
[back to top]

children()

Get an array of all child components
    var kids = myComponent.children();

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 282
[back to top]

clearInterval( intervalId )
Clears an interval and removes the associated dispose listener
Parameters

name
Type
Required
Description

intervalId
Number
yes
The id of the interval to clear

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 1295
[back to top]

clearTimeout( timeoutId )
Clears a timeout and removes the associated dispose listener
Parameters

name
Type
Required
Description

timeoutId
Number
yes
The id of the timeout to clear

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 1252
[back to top]

contentEl()
Return the component's DOM element where children are inserted.
Will either be the same as el() or a new element defined in createEl().
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 245
[back to top]

dimensions( width, height )
Set both width and height at the same time
Parameters

name
Type
Required
Description

width
Number|String
yes
Width of player

height
Number|String
yes
Height of player

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 1015
[back to top]

dispose()
Dispose of the component and all child components
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 101
[back to top]

el()

Get the component's DOM element
    var domEl = myComponent.el();

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 195
[back to top]

enableTouchActivity()
Report user touch activity when touch events occur
User activity is used to determine when controls should show/hide. It's
relatively simple when it comes to mouse events, because any mouse event
should show the controls. So we capture mouse events that bubble up to the
player and report activity when that happens.
With touch events it isn't as easy. We can't rely on touch events at the
player level, because a tap (touchstart + touchend) on the video itself on
mobile devices is meant to turn controls off (and on). User activity is
checked asynchronously, so what could happen is a tap event on the video
turns the controls off, then the touchend event bubbles up to the player,
which if it reported user activity, would turn the controls right back on.
(We also don't want to completely block touch events from bubbling up)
Also a touchmove, touch+hold, and anything other than a tap is not supposed
to turn the controls back on on a mobile device.
Here we're setting the default component behavior to report user activity
whenever touch events happen, and this can be turned off by components that
want touch events to act differently.
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 1174
[back to top]

getChild()
Returns a child component with the provided name
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 305
[back to top]

getChildById()
Returns a child component with the provided ID
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 295
[back to top]

height( num, [skipListeners] )
Get or set the height of the component (CSS values)
Setting the video tag dimension values only works with values in pixels.
Percent values will not work.
Some percents can be used, but width()/height() will return the number + %,
not the actual computed width/height.
Parameters

name
Type
Required
Description

num
Number|String
yes
New component height

skipListeners
Boolean
no
Skip the resize event trigger

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 998
[back to top]

hide()
Hide the component element if currently showing
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 944
[back to top]

id()

Get the component's ID
    var id = myComponent.id();

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 256
[back to top]

initChildren()

Add and initialize default child components from options
    // when an instance of MyComponent is created, all children in options
    // will be added to the instance by their name strings and options
    MyComponent.prototype.options_ = {
      children: [
        'myChildComponent'
      ],
      myChildComponent: {
        myChildOption: true
      }
    };

    // Or when creating the component
    var myComp = new MyComponent(player, {
      children: [
        'myChildComponent'
      ],
      myChildComponent: {
        myChildOption: true
      }
    });
The children option can also be an array of
child options objects (that also include a 'name' key).
This can be used if you have two child components of the
same type that need different options.
    var myComp = new MyComponent(player, {
      children: [
        'button',
        {
          name: 'button',
          someOtherOption: true
        },
        {
          name: 'button',
          someOtherOption: false
        }
      ]
    });

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 455
[back to top]

name()

Get the component's name. The name is often used to reference the component.
    var name = myComponent.name();

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 269
[back to top]

options( obj )

Deep merge of options objects
Whenever a property is an object on both options objects
the two properties will be merged using mergeOptions.
    Parent.prototype.options_ = {
      optionSet: {
        'childOne': { 'foo': 'bar', 'asdf': 'fdsa' },
        'childTwo': {},
        'childThree': {}
      }
    }
    newOptions = {
      optionSet: {
        'childOne': { 'foo': 'baz', 'abc': '123' }
        'childTwo': null,
        'childFour': {}
      }
    }

    this.options(newOptions);
RESULT
    {
      optionSet: {
        'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' },
        'childTwo': null, // Disabled. Won't be initialized.
        'childThree': {},
        'childFour': {}
      }
    }

Parameters

name
Type
Required
Description

obj
Object
yes
Object of new option values

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 145
[back to top]

player()
Return the component's player
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 135
[back to top]

ready( fn, sync )
Bind a listener to the component's ready state.
Different from event listeners in that if the ready event has already happened
it will trigger the function immediately.
Parameters

name
Type
Required
Description

fn
function
yes
Ready listener

sync
Boolean
yes
Exec the listener synchronously if component is ready

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 787
[back to top]

removeChild( component )
Remove a child component from this component's list of children, and the
child component's element from this component's element
Parameters

name
Type
Required
Description

component
Component
yes
Component to remove

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 415
[back to top]

setInterval( fn, interval )
Creates an interval and sets up disposal automatically.
Parameters

name
Type
Required
Description

fn
function
yes
The function to run every N seconds.

interval
Number
yes
Number of ms to delay before executing specified function.

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 1271
[back to top]

setTimeout( fn, timeout )
Creates timeout and sets up disposal automatically.
Parameters

name
Type
Required
Description

fn
function
yes
The function to run after the timeout.

timeout
Number
yes
Number of ms to delay before executing specified function.

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 1227
[back to top]

show()
Show the component element if hidden
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 933
[back to top]

toggleClass( classToToggle, [predicate] )
Add or remove a CSS class name from the component's element
Parameters

name
Type
Required
Description

classToToggle
String

predicate
Boolean|function
no
Can be a function that returns a Boolean. If true, the class
        will be added; if false, the class will be removed. If not
        given, the class will be added if not present and vice versa.

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 916
[back to top]

triggerReady()
Trigger the ready listeners
Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 814
[back to top]

width( num, skipListeners )
Set or get the width of the component (CSS values)
Setting the video tag dimension values only works with values in pixels.
Percent values will not work.
Some percents can be used, but width()/height() will return the number + %,
not the actual computed width/height.
Parameters

name
Type
Required
Description

num
Number|String
yes
Optional width number

skipListeners
Boolean
yes
Skip the 'resize' event trigger

Defined in https://github.com/videojs/video.js/blob/master/src/js/component.js line number: 981
[back to top]