/*
 * L.Circle is a circle overlay (with a certain radius in meters).
 */

L.Circle = L.Path.extend({
	initialize: function(latlng, radius, options) {
		L.Path.prototype.initialize.call(this, options);

		this._latlng = latlng;
		this._mRadius = radius;
	},

	options: {
		fill: true
	},

	projectLatlngs: function() {
		var equatorLength = 40075017,
			scale = this._map.options.scaling(this._map._zoom);

		this._point = this._map.latLngToLayerPoint(this._latlng);
		this._radius = (this._mRadius / equatorLength) * scale;
	},

	getPathString: function() {
		var p = this._point,
			r = this._radius;

		if (L.Path.SVG) {
			return "M" + p.x + "," + (p.y - r) +
					"A" + r + "," + r + ",0,1,1," +
					(p.x - 0.1) + "," + (p.y - r) + " z";
		} else {
			p._round();
			r = Math.round(r);
			return "AL " + p.x + "," + p.y + " " + r + "," + r + " 0," + (65535 * 360);
		}
	}
});


return (s && (typeof s.adj == 'object'));

L.Path = !L.Path.VML? L.Path : L.Path.extend({

keep keep keep keep keep replace keep keep keep keep keep

L.Path = L.Path.SVG || !L.Path.VML ? L.Path : L.Path.extend({

L.Polyline = L.Path.extend({
	initialize: function(latlngs, options) {
		L.Path.prototype.initialize.call(this, options);
		this._latlngs = latlngs;
	},

	options: {
		// how much to simplify the polyline on each zoom level
		// more = better performance and smoother look, less = more accurate
		smoothFactor: 1.0,
		noClip: false,

		updateOnMoveEnd: true
	},

	projectLatlngs: function() {
		this._originalPoints = [];

		for (var i = 0, len = this._latlngs.length; i < len; i++) {
			this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
		}
	},

	getPathString: function() {
		for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
			str += this._getPathPartStr(this._parts[i]);
		}
		return str;
	},

	getLatLngs: function() {
		return this._latlngs;
	},

	setLatLngs: function(latlngs) {
		this._latlngs = latlngs;
		this._redraw();
		return this;
	},

	addLatLng: function(latlng) {
		this._latlngs.push(latlng);
		this._redraw();
		return this;
	},

	spliceLatLngs: function(index, howMany) {
		var removed = [].splice.apply(this._latlngs, arguments);
		this._redraw();
		return removed;
	},

	_redraw: function() {
		this.projectLatlngs();
		this._updatePath();
	},

	_getPathPartStr: function(points) {
		var round = L.Path.VML;

		for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
			p = points[j];
			if (round) p._round();
			str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
		}
		return str;
	},

	_clipPoints: function() {
		var points = this._originalPoints,
			len = points.length,
			i, k, segment;

		if (this.options.noClip) {
			this._parts = [points];
			return;
		}

		this._parts = [];

		var parts = this._parts,
			vp = this._map._pathViewport,
			lu = L.LineUtil;

		for (i = 0, k = 0; i < len - 1; i++) {
			segment = lu.clipSegment(points[i], points[i+1], vp, i);
			if (!segment) continue;

			parts[k] = parts[k] || [];
			parts[k].push(segment[0]);

			// if segment goes out of screen, or it's the last one, it's the end of the line part
			if ((segment[1] != points[i+1]) || (i == len - 2)) {
				parts[k].push(segment[1]);
				k++;
			}
		}
	},

	// simplify each clipped part of the polyline
	_simplifyPoints: function() {
		var parts = this._parts,
			lu = L.LineUtil;

		for (var i = 0, len = parts.length; i < len; i++) {
			parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
		}
	},

	_updatePath: function() {
		this._clipPoints();
		this._simplifyPoints();

		L.Path.prototype._updatePath.call(this);
	}
});


describe("Projection.Mercator", function() {
	var p = L.Projection.Mercator;

	beforeEach(function() {
		function almostEqual(a, b, p) {
			return Math.abs(a - b) <= (p || 1.0E-12);
		};
		this.addMatchers({
			toAlmostEqual: function(expected, margin) {
				var p1 = this.actual,
					p2 = expected;
				return almostEqual(p1.x, p2.x, margin) && almostEqual(p1.y, p2.y, margin);
			}
		});
	});

	describe("#project", function() {
		it("should do projection properly", function() {
			//edge cases
			expect(p.project(new L.LatLng(0, 0))).toAlmostEqual(new L.Point(0, 0));
			expect(p.project(new L.LatLng(90, 180))).toAlmostEqual(new L.Point(-Math.PI, Math.PI));
			expect(p.project(new L.LatLng(-90, -180))).toAlmostEqual(new L.Point(-Math.PI, -Math.PI));

			expect(p.project(new L.LatLng(50, 30))).toAlmostEqual(new L.Point(0.523598775598, 1.010683188683));
		});
	});

	describe("#unproject", function() {
		it("should do unprojection properly", function() {
			function pr(point) {
				return p.project(p.unproject(point));
			}

			expect(pr(new L.Point(0, 0))).toAlmostEqual(new L.Point(0, 0));
			expect(pr(new L.Point(-Math.PI, Math.PI))).toAlmostEqual(new L.Point(-Math.PI, Math.PI));
			expect(pr(new L.Point(-Math.PI, -Math.PI))).toAlmostEqual(new L.Point(-Math.PI, -Math.PI));

			expect(pr(new L.Point(0.523598775598, 1.010683188683))).toAlmostEqual(new L.Point(0.523598775598, 1.010683188683));
		});
	});
});


// Requires options['kind']
options.track = {
player,
kind: options.kind,
kinds: options.kinds,
default: false,

// it is no longer necessary to store `kind` or `kinds` on the track itself

// since they are now stored in the `kinds` property of all instances of

// TextTrackMenuItem, but this will remain for backwards compatibility

/* eslint-env qunit */
import TextTrackMenuItem from '../../../../src/js/control-bar/text-track-controls/text-track-menu-item.js';
import TestHelpers from '../../test-helpers.js';

QUnit.module('TextTrackMenuItem', {
  beforeEach(assert) {
    this.player = TestHelpers.makePlayer();
  },
  afterEach(assert) {
    this.player.dispose();
  }
});

QUnit.test('clicking should enable the selected track', function(assert) {
  assert.expect(2);

  const foo = this.player.addTextTrack('captions', 'foo', 'en');

  const fooItem = new TextTrackMenuItem(this.player, {
    track: foo
  });

  assert.strictEqual(foo.mode, 'disabled', 'track "foo" begins "disabled"');

  fooItem.trigger('click');

  assert.strictEqual(foo.mode, 'showing', 'clicking set track "foo" to "showing"');

  fooItem.dispose();
});

QUnit.test('clicking should disable non-selected tracks of the same kind', function(assert) {
  assert.expect(9);

  const foo = this.player.addTextTrack('captions', 'foo', 'en');
  const bar = this.player.addTextTrack('captions', 'bar', 'es');
  const bop = this.player.addTextTrack('metadata', 'bop');

  bop.mode = 'hidden';

  const fooItem = new TextTrackMenuItem(this.player, {
    track: foo
  });

  const barItem = new TextTrackMenuItem(this.player, {
    track: bar
  });

  assert.strictEqual(foo.mode, 'disabled', 'captions track "foo" begins "disabled"');
  assert.strictEqual(bar.mode, 'disabled', 'captions track "bar" begins "disabled"');
  assert.strictEqual(bop.mode, 'hidden', 'metadata track "bop" is "hidden"');

  barItem.trigger('click');

  assert.strictEqual(foo.mode, 'disabled', 'captions track "foo" is still "disabled"');
  assert.strictEqual(bar.mode, 'showing', 'captions track "bar" is now "showing"');
  assert.strictEqual(bop.mode, 'hidden', 'metadata track "bop" is still "hidden"');

  fooItem.trigger('click');

  assert.strictEqual(foo.mode, 'showing', 'captions track "foo" is now "showing"');
  assert.strictEqual(bar.mode, 'disabled', 'captions track "bar" is now "disabled"');
  assert.strictEqual(bop.mode, 'hidden', 'metadata track "bop" is still "hidden"');

  fooItem.dispose();
  barItem.dispose();
});


<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>ChaptersButton</title><link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700" rel="stylesheet" type="text/css"/> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/styles/atelier-forest.light.min.css"/><link rel="stylesheet" type="text/css" href="css/api-docs.css"/>

API Index

ChaptersButton Methods

Class Methods

buildCSSClass

createItems

createMenu

Inherited Methods from MenuButton

createEl

handleClick

handleKeyPress

handleSubmenuKeyPress

pressButton

unpressButton

update

Inherited Methods from Button

addChild

Inherited Methods from ClickableComponent

controlText

handleBlur

handleFocus

Inherited Methods from Component

$

$$

addClass

children

clearInterval

clearTimeout

contentEl

dimensions

dispose

el

enableTouchActivity

extend

getChild

getChildById

getComponent

hasClass

height

hide

id

initChildren

name

off

on

one

options

player

ready

registerComponent

removeChild

removeClass

setInterval

setTimeout

show

toggleClass

trigger

triggerReady

width

ChaptersButton

The button component for toggling and selecting chapters
Chapters act much differently than other text tracks
Cues are navigation vs. other tracks of alternative languages

DEFINED IN: chapters-button.js line number: 14

EXTENDS: text-track-button.js

Constructor

ChaptersButton( player,[options],[ready] )

Parameters

name	Type	Required	Description

player	Object	yes	Player object

options	Object	no	Object of option names and values

ready	function	no	Ready callback function

Methods

buildCSSClass()

Allow sub components to stack CSS class names

Defined in https://github.com/videojs/video.js/blob/master/src/js/control-bar/text-track-controls/chapters-button.js line number: 32

[back to top]

createItems()

Create a menu item for each text track

Defined in https://github.com/videojs/video.js/blob/master/src/js/control-bar/text-track-controls/chapters-button.js line number: 42

[back to top]

createMenu()

Create menu from chapter buttons

Defined in https://github.com/videojs/video.js/blob/master/src/js/control-bar/text-track-controls/chapters-button.js line number: 69

[back to top]

createEl()

Create the component's DOM element

Defined in https://github.com/videojs/video.js/blob/master/src/js/menu/menu-button.js line number: 99

[back to top]

handleClick()

When you click the button it adds focus, which
will show the menu indefinitely.
So we'll remove focus when the mouse leaves the button.
Focus is needed for tab navigation.
Allow sub components to stack CSS class names

Defined in https://github.com/videojs/video.js/blob/master/src/js/menu/menu-button.js line number: 130

[back to top]

handleKeyPress( event )

Handle key press on menu

Parameters

name	Type	Required	Description

event	Object	yes	Key press event

Defined in https://github.com/videojs/video.js/blob/master/src/js/menu/menu-button.js line number: 151

[back to top]

handleSubmenuKeyPress( event )

Handle key press on submenu

Parameters

name	Type	Required	Description

event	Object	yes	Key press event

Defined in https://github.com/videojs/video.js/blob/master/src/js/menu/menu-button.js line number: 179

[back to top]

pressButton()

Makes changes based on button pressed

Defined in https://github.com/videojs/video.js/blob/master/src/js/menu/menu-button.js line number: 199

[back to top]

unpressButton()

Makes changes based on button unpressed

Defined in https://github.com/videojs/video.js/blob/master/src/js/menu/menu-button.js line number: 211

[back to top]

update()

Update menu

Defined in https://github.com/videojs/video.js/blob/master/src/js/menu/menu-button.js line number: 31

[back to top]

addChild( child, [options] ) (deprecated)

Adds a child component inside this button

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/button.js line number: 57

[back to top]

controlText( el )

create control text

Parameters

name	Type	Required	Description

el	Element	yes	Parent element for the control text

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

[back to top]

handleBlur()

Handle Blur - Remove keyboard triggers

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

[back to top]

handleFocus()

Handle Focus - Add keyboard functionality to element

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

[back to top]

$( selector, [context] )

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

Parameters

name	Type	Required	Description

selector	String	yes	A valid CSS selector, which will be passed to querySelector.

context	Element|String	no	A DOM element within which to query. Can also be a selector
        string in which case the first matching element will be used
        as context. If missing (or no element matches selector), falls
        back to document.

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

name	Type	Required	Description

selector	String	yes	A valid CSS selector, which will be passed to querySelectorAll.

context	Element|String	no	A DOM element within which to query. Can also be a selector
        string in which case the first matching element will be used
        as context. If missing (or no element matches selector), falls
        back to document.

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

[back to top]

addClass( classToAdd )

Add a CSS class name to the component's element

Parameters

name	Type	Required	Description

classToAdd	String	yes	Classname to add

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

[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]

static extend( props ) (deprecated)

Sets up the constructor using the supplied init method
or uses the init of the parent object

Parameters

name	Type	Required	Description

props	Object	yes	An object of properties

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

[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]

static getComponent( name )

Gets a component by name

Parameters

name	Type	Required	Description

name	String	yes	Name of the component to get

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

[back to top]

hasClass( classToCheck )

Check if a component's element has a CSS class name

Parameters

name	Type	Required	Description

classToCheck	String	yes	Classname to check

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

[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]

off( first, second, [third] )

Remove an event listener from this component's element

    myComponent.off('eventType', myFunc);

If myFunc is excluded, ALL listeners for the event type will be removed.
If eventType is excluded, ALL listeners will be removed from the component.
Alternatively you can use off to remove listeners that were added to other
elements or components using myComponent.on(otherComponent....
In this case both the event type and listener function are REQUIRED.

    myComponent.off(otherElement, 'eventType', myFunc);
    myComponent.off(otherComponent, 'eventType', myFunc);

Parameters

name	Type	Required	Description

first	String|Component	yes	The event type or other component

second	function|String	yes	The listener function or event type

third	function	no	The listener for other component

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

[back to top]

on( first, second, third )

Add an event listener to this component's element

    var myFunc = function(){
      var myComponent = this;
      // Do something when the event is fired
    };

    myComponent.on('eventType', myFunc);

The context of myFunc will be myComponent unless previously bound.
Alternatively, you can add a listener to another element or component.

    myComponent.on(otherElement, 'eventName', myFunc);
    myComponent.on(otherComponent, 'eventName', myFunc);

The benefit of using this over VjsEvents.on(otherElement, 'eventName', myFunc)
and otherComponent.on('eventName', myFunc) is that this way the listeners
will be automatically cleaned up when either component is disposed.
It will also bind myComponent as the context of myFunc.
NOTE: When using this on elements in the page other than window
and document (both permanent), if you remove the element from the DOM
you need to call myComponent.trigger(el, 'dispose') on it to clean up
references to it and allow the browser to garbage collect it.

Parameters

name	Type	Required	Description

first	String|Component	yes	The event type or other component

second	function|String	yes	The event handler or event type

third	function	yes	The event handler

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

[back to top]

one( first, second, [third] )

Add an event listener to be triggered only once and then removed

    myComponent.one('eventName', myFunc);

Alternatively you can add a listener to another element or component
that will be triggered only once.

    myComponent.one(otherElement, 'eventName', myFunc);
    myComponent.one(otherComponent, 'eventName', myFunc);

Parameters

name	Type	Required	Description

first	String|Component	yes	The event type or other component

second	function|String	yes	The listener function or event type

third	function	no	The listener function for other component

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

[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]

static registerComponent( name, comp )

Registers a component

Parameters

name	Type	Required	Description

name	String	yes	Name of the component to register

comp	Object	yes	The component to register

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

[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]

removeClass( classToRemove )

Remove a CSS class name from the component's element

Parameters

name	Type	Required	Description

classToRemove	String	yes	Classname to remove

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

[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]

trigger( event, [hash] )

Trigger an event on an element

    myComponent.trigger('eventName');
    myComponent.trigger({'type':'eventName'});
    myComponent.trigger('eventName', {data: 'some data'});
    myComponent.trigger({'type':'eventName'}, {data: 'some data'});

Parameters

name	Type	Required	Description

event	Event|Object|String	yes	A string (the type) or an event object with a type attribute

hash	Object	no	data hash to pass along with the event

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

[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]


/**
 * @file track-button.js
 */
import MenuButton from '../menu/menu-button.js';
import Component from '../component.js';
import * as Fn from '../utils/fn.js';

/**
 * The base class for buttons that toggle specific  track types (e.g. subtitles).
 *
 * @extends MenuButton
 */
class TrackButton extends MenuButton {

  /**
   * Creates an instance of this class.
   *
   * @param {Player} player
   *        The `Player` that this class should be attached to.
   *
   * @param {Object} [options]
   *        The key/value store of player options.
   */
  constructor(player, options) {
    const tracks = options.tracks;

    super(player, options);

    if (this.items.length <= 1) {
      this.hide();
    }

    if (!tracks) {
      return;
    }

    const updateHandler = Fn.bind(this, this.update);

    tracks.addEventListener('removetrack', updateHandler);
    tracks.addEventListener('addtrack', updateHandler);
    this.player_.on('ready', updateHandler);

    this.player_.on('dispose', function() {
      tracks.removeEventListener('removetrack', updateHandler);
      tracks.removeEventListener('addtrack', updateHandler);
    });
  }

}

Component.registerComponent('TrackButton', TrackButton);
export default TrackButton;


// only add tracks that are of an appropriate kind and have a label

if (this.kinds_.indexOf(track.kind) > -1) {

const item = new TrackMenuItem(this.player_, {

// MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)

keep keep keep keep add keep keep keep keep


Аудио проигрыватель

Видео проигрыватель

Воспроизвести

Приостановить

Воспроизвести снова

Текущее время

Продолжительность

Оставшееся время

Индикатор загрузки

Полноэкранный режим

Неполноэкранный режим

Скорость воспроизведения

Субтитры выкл.

Подписи выкл.

Отключить описания

Звуковая дорожка

Уровень громкости

Вы прервали воспроизведение видео

Ошибка сети вызвала сбой во время загрузки видео.

Невозможно загрузить видео из-за сетевого или серверного сбоя либо формат не поддерживается.

Воспроизведение видео было приостановлено из-за повреждения либо в связи с тем, что видео использует функции, неподдерживаемые вашим браузером.

Совместимые источники для этого видео отсутствуют.

Видео в зашифрованном виде, и у нас нет ключей для расшифровки.

Воспроизвести видео

Закрыть модальное окно

Модальное окно

Это модальное окно

Модальное окно можно закрыть нажав Esc или кнопку закрытия окна.

, откроется диалог настройки подписей

, откроется диалог настройки субтитров

, откроется диалог настройки описаний

настройки подписей

настройки субтитров

настройки описаний

Текст

Context: Фон

Полупрозрачный

Прозрачность

Размер шрифта

Стиль края текста

Пропорциональный без засечек

Моноширинный без засечек

Пропорциональный с засечками

Моноширинный с засечками

Малые прописные

сбросить все найстройки по умолчанию

Диалог настроек подписи

Начало диалоговго окна. Кнопка Escape закроет или отменит окно

Конец диалогового окна.

{1} загружается.


/**
 * @file resize-manager.js
 */
import window from 'global/window';
import { debounce } from './utils/fn.js';
import * as Events from './utils/events.js';
import mergeOptions from './utils/merge-options.js';
import Component from './component.js';

/**
 * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
 *
 * It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}.
 *
 * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
 * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
 * @example <caption>How to disable the resize manager</caption>
 * const player = videojs('#vid', {
 *   resizeManager: false
 * });
 *
 * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
 *
 * @extends Component
 */
class ResizeManager extends Component {

  /**
   * Create the ResizeManager.
   *
   * @param {Object} player
   *        The `Player` that this class should be attached to.
   *
   * @param {Object} [options]
   *        The key/value store of ResizeManager options.
   *
   * @param {Object} [options.ResizeObserver]
   *        A polyfill for ResizeObserver can be passed in here.
   *        If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
   */
  constructor(player, options) {
    let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;

    // if `null` was passed, we want to disable the ResizeObserver
    if (options.ResizeObserver === null) {
      RESIZE_OBSERVER_AVAILABLE = false;
    }

    // Only create an element when ResizeObserver isn't available
    const options_ = mergeOptions({
      createEl: !RESIZE_OBSERVER_AVAILABLE,
      reportTouchActivity: false
    }, options);

    super(player, options_);

    this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
    this.loadListener_ = null;
    this.resizeObserver_ = null;
    this.debouncedHandler_ = debounce(() => {
      this.resizeHandler();
    }, 100, false, this);

    if (RESIZE_OBSERVER_AVAILABLE) {
      this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
      this.resizeObserver_.observe(player.el());

    } else {
      this.loadListener_ = () => {
        if (!this.el_ || !this.el_.contentWindow) {
          return;
        }

        const debouncedHandler_ = this.debouncedHandler_;
        let unloadListener_ = this.unloadListener_ = function() {
          Events.off(this, 'resize', debouncedHandler_);
          Events.off(this, 'unload', unloadListener_);

          unloadListener_ = null;
        };

        // safari and edge can unload the iframe before resizemanager dispose
        // we have to dispose of event handlers correctly before that happens
        Events.on(this.el_.contentWindow, 'unload', unloadListener_);
        Events.on(this.el_.contentWindow, 'resize', debouncedHandler_);
      };

      this.one('load', this.loadListener_);
    }
  }

  createEl() {
    return super.createEl('iframe', {
      className: 'vjs-resize-manager',
      tabIndex: -1
    }, {
      'aria-hidden': 'true'
    });
  }

  /**
   * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
   *
   * @fires Player#playerresize
   */
  resizeHandler() {
    /**
     * Called when the player size has changed
     *
     * @event Player#playerresize
     * @type {EventTarget~Event}
     */
    // make sure player is still around to trigger
    // prevents this from causing an error after dispose
    if (!this.player_ || !this.player_.trigger) {
      return;
    }

    this.player_.trigger('playerresize');
  }

  dispose() {
    if (this.debouncedHandler_) {
      this.debouncedHandler_.cancel();
    }

    if (this.resizeObserver_) {
      if (this.player_.el()) {
        this.resizeObserver_.unobserve(this.player_.el());
      }
      this.resizeObserver_.disconnect();
    }

    if (this.loadListener_) {
      this.off('load', this.loadListener_);
    }

    if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
      this.unloadListener_.call(this.el_.contentWindow);
    }

    this.ResizeObserver = null;
    this.resizeObserver = null;
    this.debouncedHandler_ = null;
    this.loadListener_ = null;
    super.dispose();
  }

}

Component.registerComponent('ResizeManager', ResizeManager);
export default ResizeManager;


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <script src="//use.edgefonts.net/source-code-pro.js"></script>
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>
        <!-- there are many other style for highlighted code here: https://cdnjs.com/libraries/highlight.js -->
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/styles/atelier-forest.light.min.css">
        <link rel="stylesheet" type="text/css" href="css/api-docs.css">
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
    </head>
    <body>
        <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/highlight.min.js"></script>
        <script src="js/doc-data.js"></script>
    </body>
</html>


this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);

/**
 * @file text-track-menu-item.js
 */
import MenuItem from '../../menu/menu-item.js';
import Component from '../../component.js';
import window from 'global/window';
import document from 'global/document';

/**
 * The specific menu item type for selecting a language within a text track kind
 *
 * @extends MenuItem
 */
class TextTrackMenuItem extends MenuItem {

  /**
   * Creates an instance of this class.
   *
   * @param {Player} player
   *        The `Player` that this class should be attached to.
   *
   * @param {Object} [options]
   *        The key/value store of player options.
   */
  constructor(player, options) {
    const track = options.track;
    const tracks = player.textTracks();

    // Modify options for parent MenuItem class's init.
    options.label = track.label || track.language || 'Unknown';
    options.selected = track.mode === 'showing';

    super(player, options);

    this.track = track;
    const changeHandler = (...args) => {
      this.handleTracksChange.apply(this, args);
    };
    const selectedLanguageChangeHandler = (...args) => {
      this.handleSelectedLanguageChange.apply(this, args);
    };

    player.on(['loadstart', 'texttrackchange'], changeHandler);
    tracks.addEventListener('change', changeHandler);
    tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
    this.on('dispose', function() {
      player.off(['loadstart', 'texttrackchange'], changeHandler);
      tracks.removeEventListener('change', changeHandler);
      tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
    });

    // iOS7 doesn't dispatch change events to TextTrackLists when an
    // associated track's mode changes. Without something like
    // Object.observe() (also not present on iOS7), it's not
    // possible to detect changes to the mode attribute and polyfill
    // the change event. As a poor substitute, we manually dispatch
    // change events whenever the controls modify the mode.
    if (tracks.onchange === undefined) {
      let event;

      this.on(['tap', 'click'], function() {
        if (typeof window.Event !== 'object') {
          // Android 2.3 throws an Illegal Constructor error for window.Event
          try {
            event = new window.Event('change');
          } catch (err) {
            // continue regardless of error
          }
        }

        if (!event) {
          event = document.createEvent('Event');
          event.initEvent('change', true, true);
        }

        tracks.dispatchEvent(event);
      });
    }

    // set the default state based on current tracks
    this.handleTracksChange();
  }

  /**
   * This gets called when an `TextTrackMenuItem` is "clicked". See
   * {@link ClickableComponent} for more detailed information on what a click can be.
   *
   * @param {EventTarget~Event} event
   *        The `keydown`, `tap`, or `click` event that caused this function to be
   *        called.
   *
   * @listens tap
   * @listens click
   */
  handleClick(event) {
    const referenceTrack = this.track;
    const tracks = this.player_.textTracks();

    super.handleClick(event);

    if (!tracks) {
      return;
    }

    // Determine the relevant kind(s) of tracks for this component and filter
    // out empty kinds.
    const kinds = (referenceTrack.kinds || [referenceTrack.kind]).filter(Boolean);

    for (let i = 0; i < tracks.length; i++) {
      const track = tracks[i];

      // If the track from the text tracks list is not of the right kind,
      // skip it. We do not want to affect tracks of incompatible kind(s).
      if (kinds.indexOf(track.kind) === -1) {
        continue;
      }

      // If this text track is the component's track and it is not showing,
      // set it to showing.
      if (track === referenceTrack) {
        if (track.mode !== 'showing') {
          track.mode = 'showing';
        }

      // If this text track is not the component's track and it is not
      // disabled, set it to disabled.
      } else if (track.mode !== 'disabled') {
        track.mode = 'disabled';
      }
    }
  }

  /**
   * Handle text track list change
   *
   * @param {EventTarget~Event} event
   *        The `change` event that caused this function to be called.
   *
   * @listens TextTrackList#change
   */
  handleTracksChange(event) {
    const shouldBeSelected = this.track.mode === 'showing';

    // Prevent redundant selected() calls because they may cause
    // screen readers to read the appended control text unnecessarily
    if (shouldBeSelected !== this.isSelected_) {
      this.selected(shouldBeSelected);
    }
  }

  handleSelectedLanguageChange(event) {
    if (this.track.mode === 'showing') {
      const selectedLanguage = this.player_.cache_.selectedLanguage;

      // Don't replace the kind of track across the same language
      if (selectedLanguage && selectedLanguage.enabled &&
        selectedLanguage.language === this.track.language &&
        selectedLanguage.kind !== this.track.kind) {
        return;
      }

      this.player_.cache_.selectedLanguage = {
        enabled: true,
        language: this.track.language,
        kind: this.track.kind
      };
    }
  }

  dispose() {
    // remove reference to track object on dispose
    this.track = null;

    super.dispose();
  }

}

Component.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
export default TextTrackMenuItem;


# Video Tracks

> **Note:** While video tracks [are a standard][spec-videotrack], there are no compatible implementations at this time. This is an experimental technology!

Video tracks are a feature of HTML5 video for providing alternate video tracks to the user, so they can change the type of video they want to watch. Video.js offers a cross-browser implementation of video tracks.

## Table of Contents

* [Caveats](#caveats)
* [Working with Video Tracks](#working-with-video-tracks)
  * [Add a Video Track to the Player](#add-a-video-track-to-the-player)
  * [Listen for a Video Track Becoming Enabled](#listen-for-a-video-track-becoming-enabled)
  * [Removing an Video Track from the Player](#removing-an-video-track-from-the-player)
* [API](#api)
  * [videojs.VideoTrack](#videojsvideotrack)
    * [id](#id)
    * [kind](#kind)
    * [label](#label)
    * [language](#language)
    * [selected](#selected)

## Caveats

* It is not possible to add video tracks through HTML like you can with text tracks. They must be added programmatically.
* Video.js only stores track representations. Switching video tracks for playback is _not handled by Video.js_ and must be handled elsewhere.

## Working with Video Tracks

### Add a Video Track to the Player

```js
// Create a player.
var player = videojs('my-player');

// Create a track object.
var track = new videojs.VideoTrack({
  id: 'my-alternate-video-track',
  kind: 'commentary',
  label: 'Director\'s Commentary',
  language: 'en'
});

// Add the track to the player's video track list.
player.videoTracks().addTrack(track);
```

### Listen for a Video Track Becoming Enabled

When a track is enabled or disabled on an `VideoTrackList`, a `change` event will be fired. You can listen for that event and do something with it.

> NOTE: The initial `VideoTrack` selection (usually the main track that is selected) should not fire a `change` event.

```js
// Get the current player's VideoTrackList object.
var videoTrackList = player.videoTracks();

// Listen to the "change" event.
videoTrackList.addEventListener('change', function() {

  // Log the currently enabled VideoTrack label.
  for (var i = 0; i < videoTrackList.length; i++) {
    var track = videoTrackList[i];

    if (track.enabled) {
      videojs.log(track.label);
      return;
    }
  }
});
```

### Removing an Video Track from the Player

Assuming a player already exists and has an video track that you want to remove, you might do something like the following:

```js
// Get the track we created in an earlier example.
var track = player.videoTracks().getTrackById('my-alternate-video-track');

// Remove it from the video track list.
player.videoTracks().removeTrack(track);
```

## API

For more complete information, refer to the [Video.js API docs](https://docs.videojs.com/), specifically:

* `Player#videoTracks`
* `VideoTrackList`
* `VideoTrack`

### `videojs.VideoTrack`

This class is based on [the `VideoTrack` standard][spec-videotrack] and can be used to create new video track objects.

Each property below is available as an option to the `VideoTrack` constructor.

#### `id`

> [standard definition](https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-id)

A unique identifier for this track. Video.js will generate one if not given.

#### `kind`

> [standard definition](https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind)

Video.js supports standard `kind` values for `VideoTracks`:

* `"alternative"`: A possible alternative to the main track.
* `"captions"`: The main video track with burned in captions
* `"main"`: The main video track.
* `"sign"`: The main video track with added sign language overlay.
* `"subtitles"`: The main video track with burned in subtitles.
* `"commentary"`: The main video track with burned in commentary.
* `""` (default): No explicit kind, or the kind given by the track's metadata is not recognized by the user agent.

#### `label`

> [standard definition](https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-label)

The label for the track that will be shown to the user. For example, in a menu that lists the different captions available as alternate video tracks.

#### `language`

> [standard definition](https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-language)

The valid [BCP 47](https://tools.ietf.org/html/bcp47) code for the language of the video track, e.g. `"en"` for English or `"es"` for Spanish.

For supported language translations, please see the [languages folder (/lang)](https://github.com/videojs/video.js/tree/master/lang) folder located in the Video.js root and refer to the [languages guide](/docs/guides/languages.md) for more information on languages in Video.js.

#### `selected`

> [standard definition](https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-selected)

Whether or not this track should be playing. Only one video track may be selected at a time.

[spec-videotrack]: https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack


/**
 * @file track-list.js
 */
import EventTarget from '../event-target';

/**
 * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
 * {@link VideoTrackList}
 *
 * @extends EventTarget
 */
class TrackList extends EventTarget {
  /**
   * Create an instance of this class
   *
   * @param {Track[]} tracks
   *        A list of tracks to initialize the list with.
   *
   * @abstract
   */
  constructor(tracks = []) {
    super();

    this.tracks_ = [];

    /**
     * @memberof TrackList
     * @member {number} length
     *         The current number of `Track`s in the this Trackist.
     * @instance
     */
    Object.defineProperty(this, 'length', {
      get() {
        return this.tracks_.length;
      }
    });

    for (let i = 0; i < tracks.length; i++) {
      this.addTrack(tracks[i]);
    }
  }

  /**
   * Add a {@link Track} to the `TrackList`
   *
   * @param {Track} track
   *        The audio, video, or text track to add to the list.
   *
   * @fires TrackList#addtrack
   */
  addTrack(track) {
    const index = this.tracks_.length;

    if (!('' + index in this)) {
      Object.defineProperty(this, index, {
        get() {
          return this.tracks_[index];
        }
      });
    }

    // Do not add duplicate tracks
    if (this.tracks_.indexOf(track) === -1) {
      this.tracks_.push(track);
      /**
       * Triggered when a track is added to a track list.
       *
       * @event TrackList#addtrack
       * @type {EventTarget~Event}
       * @property {Track} track
       *           A reference to track that was added.
       */
      this.trigger({
        track,
        type: 'addtrack',
        target: this
      });
    }
  }

  /**
   * Remove a {@link Track} from the `TrackList`
   *
   * @param {Track} rtrack
   *        The audio, video, or text track to remove from the list.
   *
   * @fires TrackList#removetrack
   */
  removeTrack(rtrack) {
    let track;

    for (let i = 0, l = this.length; i < l; i++) {
      if (this[i] === rtrack) {
        track = this[i];
        if (track.off) {
          track.off();
        }

        this.tracks_.splice(i, 1);

        break;
      }
    }

    if (!track) {
      return;
    }

    /**
     * Triggered when a track is removed from track list.
     *
     * @event TrackList#removetrack
     * @type {EventTarget~Event}
     * @property {Track} track
     *           A reference to track that was removed.
     */
    this.trigger({
      track,
      type: 'removetrack',
      target: this
    });
  }

  /**
   * Get a Track from the TrackList by a tracks id
   *
   * @param {string} id - the id of the track to get
   * @method getTrackById
   * @return {Track}
   * @private
   */
  getTrackById(id) {
    let result = null;

    for (let i = 0, l = this.length; i < l; i++) {
      const track = this[i];

      if (track.id === id) {
        result = track;
        break;
      }
    }

    return result;
  }
}

/**
 * Triggered when a different track is selected/enabled.
 *
 * @event TrackList#change
 * @type {EventTarget~Event}
 */

/**
 * Events that can be called with on + eventName. See {@link EventHandler}.
 *
 * @property {Object} TrackList#allowedEvents_
 * @private
 */
TrackList.prototype.allowedEvents_ = {
  change: 'change',
  addtrack: 'addtrack',
  removetrack: 'removetrack'
};

// emulate attribute EventHandler support to allow for feature detection
for (const event in TrackList.prototype.allowedEvents_) {
  TrackList.prototype['on' + event] = null;
}

export default TrackList;


/**
 * @file create-logger.js
 * @module create-logger
 */
import window from 'global/window';

// This is the private tracking variable for the logging history.
let history = [];

/**
 * Log messages to the console and history based on the type of message
 *
 * @private
 * @param  {string} type
 *         The name of the console method to use.
 *
 * @param  {Array} args
 *         The arguments to be passed to the matching console method.
 */
const LogByTypeFactory = (name, log) => (type, level, args) => {
  const lvl = log.levels[level];
  const lvlRegExp = new RegExp(`^(${lvl})$`);

  if (type !== 'log') {

    // Add the type to the front of the message when it's not "log".
    args.unshift(type.toUpperCase() + ':');
  }

  // Add console prefix after adding to history.
  args.unshift(name + ':');

  // Add a clone of the args at this point to history.
  if (history) {
    history.push([].concat(args));
  }

  // If there's no console then don't try to output messages, but they will
  // still be stored in history.
  if (!window.console) {
    return;
  }

  // Was setting these once outside of this function, but containing them
  // in the function makes it easier to test cases where console doesn't exist
  // when the module is executed.
  let fn = window.console[type];

  if (!fn && type === 'debug') {
    // Certain browsers don't have support for console.debug. For those, we
    // should default to the closest comparable log.
    fn = window.console.info || window.console.log;
  }

  // Bail out if there's no console or if this type is not allowed by the
  // current logging level.
  if (!fn || !lvl || !lvlRegExp.test(type)) {
    return;
  }

  fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
};

export default function createLogger(name) {
  // This is the private tracking variable for logging level.
  let level = 'info';

  // the curried logByType bound to the specific log and history
  let logByType;

  /**
   * Logs plain debug messages. Similar to `console.log`.
   *
   * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
   * of our JSDoc template, we cannot properly document this as both a function
   * and a namespace, so its function signature is documented here.
   *
   * #### Arguments
   * ##### *args
   * Mixed[]
   *
   * Any combination of values that could be passed to `console.log()`.
   *
   * #### Return Value
   *
   * `undefined`
   *
   * @namespace
   * @param    {Mixed[]} args
   *           One or more messages or objects that should be logged.
   */
  const log = function(...args) {
    logByType('log', level, args);
  };

  // This is the logByType helper that the logging methods below use
  logByType = LogByTypeFactory(name, log);

  /**
   * Create a new sublogger which chains the old name to the new name.
   *
   * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
   * ```js
   *  mylogger('foo');
   *  // > VIDEOJS: player: foo
   * ```
   *
   * @param {string} name
   *        The name to add call the new logger
   * @return {Object}
   */
  log.createLogger = (subname) => createLogger(name + ': ' + subname);

  /**
   * Enumeration of available logging levels, where the keys are the level names
   * and the values are `|`-separated strings containing logging methods allowed
   * in that logging level. These strings are used to create a regular expression
   * matching the function name being called.
   *
   * Levels provided by Video.js are:
   *
   * - `off`: Matches no calls. Any value that can be cast to `false` will have
   *   this effect. The most restrictive.
   * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
   *   `log.warn`, and `log.error`).
   * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
   * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
   * - `warn`: Matches `log.warn` and `log.error` calls.
   * - `error`: Matches only `log.error` calls.
   *
   * @type {Object}
   */
  log.levels = {
    all: 'debug|log|warn|error',
    off: '',
    debug: 'debug|log|warn|error',
    info: 'log|warn|error',
    warn: 'warn|error',
    error: 'error',
    DEFAULT: level
  };

  /**
   * Get or set the current logging level.
   *
   * If a string matching a key from {@link module:log.levels} is provided, acts
   * as a setter.
   *
   * @param  {string} [lvl]
   *         Pass a valid level to set a new logging level.
   *
   * @return {string}
   *         The current logging level.
   */
  log.level = (lvl) => {
    if (typeof lvl === 'string') {
      if (!log.levels.hasOwnProperty(lvl)) {
        throw new Error(`"${lvl}" in not a valid log level`);
      }
      level = lvl;
    }
    return level;
  };

  /**
   * Returns an array containing everything that has been logged to the history.
   *
   * This array is a shallow clone of the internal history record. However, its
   * contents are _not_ cloned; so, mutating objects inside this array will
   * mutate them in history.
   *
   * @return {Array}
   */
  log.history = () => history ? [].concat(history) : [];

  /**
   * Allows you to filter the history by the given logger name
   *
   * @param {string} fname
   *        The name to filter by
   *
   * @return {Array}
   *         The filtered list to return
   */
  log.history.filter = (fname) => {
    return (history || []).filter((historyItem) => {
      // if the first item in each historyItem includes `fname`, then it's a match
      return new RegExp(`.*${fname}.*`).test(historyItem[0]);
    });
  };

  /**
   * Clears the internal history tracking, but does not prevent further history
   * tracking.
   */
  log.history.clear = () => {
    if (history) {
      history.length = 0;
    }
  };

  /**
   * Disable history tracking if it is currently enabled.
   */
  log.history.disable = () => {
    if (history !== null) {
      history.length = 0;
      history = null;
    }
  };

  /**
   * Enable history tracking if it is currently disabled.
   */
  log.history.enable = () => {
    if (history === null) {
      history = [];
    }
  };

  /**
   * Logs error messages. Similar to `console.error`.
   *
   * @param {Mixed[]} args
   *        One or more messages or objects that should be logged as an error
   */
  log.error = (...args) => logByType('error', level, args);

  /**
   * Logs warning messages. Similar to `console.warn`.
   *
   * @param {Mixed[]} args
   *        One or more messages or objects that should be logged as a warning.
   */
  log.warn = (...args) => logByType('warn', level, args);

  /**
   * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
   * log if `console.debug` is not available
   *
   * @param {Mixed[]} args
   *        One or more messages or objects that should be logged as debug.
   */
  log.debug = (...args) => logByType('debug', level, args);

  return log;
}


// Determine the relevant kind(s) of tracks for this component and filter

const kinds = (referenceTrack.kinds || [referenceTrack.kind]).filter(Boolean);

for (let i = 0; i < tracks.length; i++) {

// If the track from the text tracks list is not of the right kind,

// skip it. We do not want to affect tracks of incompatible kind(s).

keep keep keep replace replace replace replace keep keep keep keep keep


Buscando directo, actualmente tras en directo

Buscando directo, actualmente reproducindo en directo

Vostede interrompeu a reprodución do medio.

Un erro de rede interrompeu a descarga do medio.

Non foi posíbel cargar o medio por mor dun fallo de rede ou do servidor ou porque o formato non é compatíbel.

Interrompeuse a reprodución do medio por mor dun problema de estragamento dos datos ou porque o medio precisa funcións que o seu navegador non ofrece.

Non se atopou ningunha orixe compatíbel con este vídeo.

O medio está cifrado e non temos as chaves para descifralo .

Este diálogo modal pódese pechar premendo a tecla Escape ou activando o botón de pechar.

, abre o diálogo de axustes dos subtítulos para xordos

, abre o diálogo de axustes das descricións

Texto

Context: Fondo

restaurar todos os axustes aos valores predeterminados

Diálogo de axustes dos subtítulos para xordos

Inicio da xanela de diálogo. A tecla Escape cancelará e pechará a xanela.


/**
 * @file custom-control-spacer.js
 */
import Spacer from './spacer.js';
import Component from '../../component.js';

/**
 * Spacer specifically meant to be used as an insertion point for new plugins, etc.
 *
 * @extends Spacer
 */
class CustomControlSpacer extends Spacer {

  /**
   * Builds the default DOM `className`.
   *
   * @return {string}
   *         The DOM `className` for this object.
   */
  buildCSSClass() {
    return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  }

  /**
   * Create the `Component`'s DOM element
   *
   * @return {Element}
   *         The element that was created.
   */
  createEl() {
    const el = super.createEl({
      className: this.buildCSSClass()
    });

    // No-flex/table-cell mode requires there be some content
    // in the cell to fill the remaining space of the table.
    el.innerHTML = '\u00a0';
    return el;
  }
}

Component.registerComponent('CustomControlSpacer', CustomControlSpacer);
export default CustomControlSpacer;


# Video.js Plugins

One of the great strengths of Video.js is its ecosystem of plugins that allow authors from all over the world to share their video player customizations. This includes everything from the simplest UI tweaks to new [playback technologies and source handlers][tech]!

Because we view plugins as such an important part of Video.js, the organization is committed to maintaining a robust set of tools for plugin authorship:

* [generator-videojs-plugin][generator]

  A [Yeoman][yeoman] generator for scaffolding a Video.js plugin project. Additionally, it offers a set of [conventions for plugin authorship][standards] that, if followed, make authorship, contribution, and usage consistent and predictable.

  In short, the generator sets up plugin authors to focus on writing their plugin - not messing with tools.

## Writing a Basic Plugin

If you've written a Video.js plugin before, the basic plugin concept should be familiar. It's similar to a jQuery plugin in that the core idea is that you're adding a method to the player.

### Write a JavaScript Function

A basic plugin is a plain JavaScript function:

```js
function examplePlugin(options) {

  if (options.customClass) {
    this.addClass(options.customClass);
  }

  this.on('playing', function() {
    videojs.log('playback began!');
  });
}
```

By convention, plugins are passed an `options` object; however, you can realistically accept whatever arguments you want. This example plugin will add a custom class (whatever is passed in as `options.customClass`) and, whenever playback begins, it will log a message to the browser console.

> **Note:** The value of `this` in the plugin function is the player instance; so, you have access to [its complete API][api-player].

### Register a Basic Plugin

Now that we have a function that does something with a player, all that's left is to register the plugin with Video.js:

```js
videojs.registerPlugin('examplePlugin', examplePlugin);
```

After that, any player will automatically have an `examplePlugin` method on its prototype!

> **Note:** The only stipulation with the name of the plugin is that it cannot conflict with any existing plugin or player method.

## Writing an Advanced Plugin

Video.js 6 introduced advanced plugins: these are plugins that share a similar API with basic plugins, but are class-based and offer a range of extra features out of the box.

While reading the following sections, you may want to refer to the [Plugin API docs][api-plugin] for more detail.

### Write a JavaScript Class/Constructor

If you're familiar with creating [components][components], this process is similar. An advanced plugin starts with a JavaScript class (a.k.a. a constructor function).

If you're using ES6 already, you can use that syntax with your transpiler/language of choice (Babel, TypeScript, etc):

```js
const Plugin = videojs.getPlugin('plugin');

class ExamplePlugin extends Plugin {

  constructor(player, options) {
    super(player, options);

    if (options.customClass) {
      player.addClass(options.customClass);
    }

    player.on('playing', function() {
      videojs.log('playback began!');
    });
  }
}
```

Or with ES5:

```js
var Plugin = videojs.getPlugin('plugin');

var ExamplePlugin = videojs.extend(Plugin, {

  constructor: function(player, options) {
    Plugin.call(this, player, options);

    if (options.customClass) {
      player.addClass(options.customClass);
    }

    player.on('playing', function() {
      videojs.log('playback began!');
    });
  }
});
```

For now, this example advanced plugin does the exact same thing as the basic plugin described above - not to worry, we will make it more interesting as we continue!

### Register an Advanced Plugin

The registration process for advanced plugins is identical to [the process for basic plugins](#register-a-basic-plugin).

```js
videojs.registerPlugin('examplePlugin', ExamplePlugin);
```

> **Note:** Because ES6 classes are syntactic sugar on top of existing constructor function and prototype architecture in JavaScript, in all cases `registerPlugin`'s second argument is a function.

### Key Differences from Basic Plugins

Advanced plugins have two key differences from basic plugins that are important to understand before describing their advanced features.

#### The Value of `this`

With basic plugins, the value of `this` in the plugin function will be the _player_.

With advanced plugins, the value of `this` is the _instance of the plugin class_. The player is passed to the plugin constructor as its first argument (and is automatically applied to the plugin instance as the `player` property) and any further arguments are passed after that.

#### The Player Plugin Name Property

Both basic plugins and advanced plugins are set up by calling a method on a player with a name matching the plugin (e.g., `player.examplePlugin()`).

However, with advanced plugins, this method acts like a factory function and it is _replaced_ for the current player by a new function which returns the plugin instance:

```js
// `examplePlugin` has not been called, so it is a factory function.
player.examplePlugin();

// `examplePlugin` is now a function that returns the same instance of
// `ExamplePlugin` that was generated by the previous call.
player.examplePlugin().someMethodName();
```

With basic plugins, the method does not change - it is always the same function. It is up to the authors of basic plugins to deal with multiple calls to their plugin function.

### Features of Advanced Plugins

Up to this point, our example advanced plugin is functionally identical to our example basic plugin. However, advanced plugins bring with them a great deal of benefit that is not built into basic plugins.

#### Events

Like components, advanced plugins offer an implementation of events. This includes:

* The ability to listen for events on the plugin instance using `on` or `one`:

  ```js
  player.examplePlugin().on('example-event', function() {
    videojs.log('example plugin received an example-event');
  });
  ```

* The ability to `trigger` custom events on a plugin instance:

  ```js
  player.examplePlugin().trigger('example-event');
  ```

* The ability to stop listening to custom events on a plugin instance using `off`:

  ```js
  player.examplePlugin().off('example-event');
  ```

By offering a built-in events system, advanced plugins offer a wider range of options for code structure with a pattern familiar to most web developers.

##### Extra Event Data

All events triggered by plugins include an additional data object as a second argument. This object has three properties:

* `name`: The name of the plugin (e.g. `"examplePlugin"`) as a string.
* `plugin`: The plugin constructor (e.g. `ExamplePlugin`).
* `instance`: The plugin constructor instance.

#### Statefulness

A new concept introduced for advanced plugins is _statefulness_. This is similar to React components' `state` property and `setState` method.

Advanced plugin instances each have a `state` property, which is a plain JavaScript object - it can contain any keys and values the plugin author wants.

A default `state` can be provided by adding a static property to a plugin constructor:

```js
ExamplePlugin.defaultState = {
  customClass: 'default-custom-class'
};
```

When the `state` is updated via the `setState` method, the plugin instance fires a `"statechanged"` event, but _only if something changed!_ This event can be used as a signal to update the DOM or perform some other action. The event object passed to listeners for this event includes, an object describing the changes that occurred on the `state` property:

```js
player.examplePlugin().on('statechanged', function(e) {
  if (e.changes && e.changes.customClass) {
    this.player
      .removeClass(e.changes.customClass.from)
      .addClass(e.changes.customClass.to);
  }
});

player.examplePlugin().setState({customClass: 'another-custom-class'});
```

#### Lifecycle

Like components, advanced plugins have a lifecycle. They can be created with their factory function and they can be destroyed using their `dispose` method:

```js
// set up a example plugin instance
player.examplePlugin();

// dispose of it anytime thereafter
player.examplePlugin().dispose();
```

The `dispose` method has several effects:

* Triggers a `"dispose"` event on the plugin instance.
* Cleans up all event listeners on the plugin instance, which helps avoid errors caused by events being triggered after an object is cleaned up.
* Removes plugin state and references to the player to avoid memory leaks.
* Reverts the player's named property (e.g. `player.examplePlugin`) _back_ to the original factory function, so the plugin can be set up again.

In addition, if the player is disposed, the disposal of all its advanced plugin instances will be triggered as well.

#### Version

Adding a version number to a plugin is done by defining a `VERSION` property on the plugin before registering it:

```js
ExamplePlugin.VERSION = '1.0.1';

videojs.registerPlugin('examplePlugin', ExamplePlugin);
```

Retrieve it using `videojs.getPluginVersion`:

```js
var version = videojs.getPluginVersion('examplePlugin');
console.log(version);  // 1.0.1
```

Note that the [plugin generator](https://github.com/videojs/generator-videojs-plugin) already takes care of adding a version number for you.

### Advanced Example Advanced Plugin

What follows is a complete ES6 advanced plugin that logs a custom message when the player's state changes between playing and pause. It uses all the described advanced features:

```js
import videojs from 'video.js';

const Plugin = videojs.getPlugin('plugin');

class Advanced extends Plugin {

  constructor(player, options) {
    super(player, options);

    // Whenever the player emits a playing or pause event, we update the
    // state if necessary.
    this.on(player, ['playing', 'pause'], this.updateState);
    this.on('statechanged', this.logState);
  }

  dispose() {
    super.dispose();
    videojs.log('the advanced plugin is being disposed');
  }

  updateState() {
    this.setState({playing: !this.player.paused()});
  }

  logState(changed) {
    videojs.log(`the player is now ${this.state.playing ? 'playing' : 'paused'}`);
  }
}

videojs.registerPlugin('advanced', Advanced);

const player = videojs('example-player');

player.advanced();

// This will begin playback, which will trigger a "playing" event, which will
// update the state of the plugin, which will cause a message to be logged.
player.play();

// This will pause playback, which will trigger a "paused" event, which will
// update the state of the plugin, which will cause a message to be logged.
player.pause();

player.advanced().dispose();

// This will begin playback, but the plugin has been disposed, so it will not
// log any messages.
player.play();
```

This example may be a bit pointless in reality, but it demonstrates the sort of flexibility offered by advanced plugins over basic plugins.

## Setting up a Plugin

There are two ways to set up (or initialize) a plugin on a player. Both ways work identically for both basic and advanced plugins.

The first way is during creation of the player. Using the `plugins` option, a plugin can be automatically set up on a player:

```js
videojs('example-player', {
  plugins: {
    examplePlugin: {
      customClass: 'example-class'
    }
  }
});
```

Otherwise, a plugin can be manually set up:

```js
var player = videojs('example-player');
player.examplePlugin({customClass: 'example-class'});
```

These two methods are functionally identical - use whichever you prefer!

### Plugin Setup Events

Occasionally, a use-case arises where some code needs to wait for a plugin to be initialized. As of Video.js 6, this can be achieved by listening for `pluginsetup` events on the player.

For any given plugin initialization, there are four events to be aware of:

* `beforepluginsetup`: Triggered immediately before any plugin is initialized.
* `beforepluginsetup:examplePlugin` Triggered immediately before the `examplePlugin` is initialized.
* `pluginsetup`: Triggered after any plugin is initialized.
* `pluginsetup:examplePlugin`: Triggered after he `examplePlugin` is initialized.

These events work for both basic and advanced plugins. They are triggered on the player and each includes an object of [extra event data](#extra-event-data) as a second argument to its listeners.

## References

* [Player API][api-player]
* [Plugin API][api-plugin]
* [Plugin Generator][generator]
* [Plugin Conventions][standards]

[components]: /docs/guides/components.md

[tech]: /docs/guides/tech.md

[api-player]: https://docs.videojs.com/Player.html

[api-plugin]: https://docs.videojs.com/Plugin.html

[generator]: https://github.com/videojs/generator-videojs-plugin

[spellbook]: https://github.com/videojs/spellbook

[standards]: https://github.com/videojs/generator-videojs-plugin/blob/master/docs/standards.md

[yeoman]: http://yeoman.io


if (this.kinds.indexOf(track.kind) === -1) {


/**
 * @file computed-style.js
 * @module computed-style
 */
import window from 'global/window';

/**
 * A safe getComputedStyle.
 *
 * This is needed because in Firefox, if the player is loaded in an iframe with
 * `display:none`, then `getComputedStyle` returns `null`, so, we do a
 * null-check to make sure that the player doesn't break in these cases.
 *
 * @function
 * @param    {Element} el
 *           The element you want the computed style of
 *
 * @param    {string} prop
 *           The property name you want
 *
 * @see      https://bugzilla.mozilla.org/show_bug.cgi?id=548397
 */
function computedStyle(el, prop) {
  if (!el || !prop) {
    return '';
  }

  if (typeof window.getComputedStyle === 'function') {
    const cs = window.getComputedStyle(el);

    return cs ? cs[prop] : '';
  }

  return '';
}

export default computedStyle;


<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>ClickableComponent</title><link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700" rel="stylesheet" type="text/css"/> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/styles/atelier-forest.light.min.css"/><link rel="stylesheet" type="text/css" href="css/api-docs.css"/>

API Index

ClickableComponent Methods

Class Methods

addChild

buildCSSClass

controlText

createEl

handleBlur

handleClick

handleFocus

handleKeyPress

Inherited Methods from Component

$

$$

addClass

children

clearInterval

clearTimeout

contentEl

dimensions

dispose

el

enableTouchActivity

extend

getChild

getChildById

getComponent

hasClass

height

hide

id

initChildren

name

off

on

one

options

player

ready

registerComponent

removeChild

removeClass

setInterval

setTimeout

show

toggleClass

trigger

triggerReady

width

ClickableComponent

Clickable Component which is clickable or keyboard actionable, but is not a native HTML button

DEFINED IN: clickable-component.js line number: 12

EXTENDS: component.js

Constructor

ClickableComponent( player,[options] )

Parameters

name	Type	Required	Description

player	Object	yes	Main Player

options	Object	no	Object of option names and values

Methods

addChild( child, [options] )

Adds a child component inside this clickable-component

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/clickable-component.js line number: 112

[back to top]

buildCSSClass()

Allows sub components to stack CSS class names

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

[back to top]

controlText( el )

create control text

Parameters

name	Type	Required	Description

el	Element	yes	Parent element for the control text

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

[back to top]

createEl( [type], [props], [attributes] )

Create the component's DOM element

Parameters

name	Type	Required	Description

type	String	no	Element's node type. e.g. 'div'

props	Object	no	An object of properties that should be set on the element

attributes	Object	no	An object of attributes that should be set on the element

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

[back to top]

handleBlur()

Handle Blur - Remove keyboard triggers

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

[back to top]

handleClick()

Handle Click - Override with specific functionality for component

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

[back to top]

handleFocus()

Handle Focus - Add keyboard functionality to element

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

[back to top]

handleKeyPress()

Handle KeyPress (document level) - Trigger click when Space or Enter key is pressed

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

[back to top]

$( selector, [context] )

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

Parameters

name	Type	Required	Description

selector	String	yes	A valid CSS selector, which will be passed to querySelector.

context	Element|String	no	A DOM element within which to query. Can also be a selector
        string in which case the first matching element will be used
        as context. If missing (or no element matches selector), falls
        back to document.

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

name	Type	Required	Description

selector	String	yes	A valid CSS selector, which will be passed to querySelectorAll.

context	Element|String	no	A DOM element within which to query. Can also be a selector
        string in which case the first matching element will be used
        as context. If missing (or no element matches selector), falls
        back to document.

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

[back to top]

addClass( classToAdd )

Add a CSS class name to the component's element

Parameters

name	Type	Required	Description

classToAdd	String	yes	Classname to add

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

[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]

static extend( props ) (deprecated)

Sets up the constructor using the supplied init method
or uses the init of the parent object

Parameters

name	Type	Required	Description

props	Object	yes	An object of properties

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

[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]

static getComponent( name )

Gets a component by name

Parameters

name	Type	Required	Description

name	String	yes	Name of the component to get

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

[back to top]

hasClass( classToCheck )

Check if a component's element has a CSS class name

Parameters

name	Type	Required	Description

classToCheck	String	yes	Classname to check

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

[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]

off( first, second, [third] )

Remove an event listener from this component's element

    myComponent.off('eventType', myFunc);

If myFunc is excluded, ALL listeners for the event type will be removed.
If eventType is excluded, ALL listeners will be removed from the component.
Alternatively you can use off to remove listeners that were added to other
elements or components using myComponent.on(otherComponent....
In this case both the event type and listener function are REQUIRED.

    myComponent.off(otherElement, 'eventType', myFunc);
    myComponent.off(otherComponent, 'eventType', myFunc);

Parameters

name	Type	Required	Description

first	String|Component	yes	The event type or other component

second	function|String	yes	The listener function or event type

third	function	no	The listener for other component

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

[back to top]

on( first, second, third )

Add an event listener to this component's element

    var myFunc = function(){
      var myComponent = this;
      // Do something when the event is fired
    };

    myComponent.on('eventType', myFunc);

The context of myFunc will be myComponent unless previously bound.
Alternatively, you can add a listener to another element or component.

    myComponent.on(otherElement, 'eventName', myFunc);
    myComponent.on(otherComponent, 'eventName', myFunc);

The benefit of using this over VjsEvents.on(otherElement, 'eventName', myFunc)
and otherComponent.on('eventName', myFunc) is that this way the listeners
will be automatically cleaned up when either component is disposed.
It will also bind myComponent as the context of myFunc.
NOTE: When using this on elements in the page other than window
and document (both permanent), if you remove the element from the DOM
you need to call myComponent.trigger(el, 'dispose') on it to clean up
references to it and allow the browser to garbage collect it.

Parameters

name	Type	Required	Description

first	String|Component	yes	The event type or other component

second	function|String	yes	The event handler or event type

third	function	yes	The event handler

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

[back to top]

one( first, second, [third] )

Add an event listener to be triggered only once and then removed

    myComponent.one('eventName', myFunc);

Alternatively you can add a listener to another element or component
that will be triggered only once.

    myComponent.one(otherElement, 'eventName', myFunc);
    myComponent.one(otherComponent, 'eventName', myFunc);

Parameters

name	Type	Required	Description

first	String|Component	yes	The event type or other component

second	function|String	yes	The listener function or event type

third	function	no	The listener function for other component

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

[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]

static registerComponent( name, comp )

Registers a component

Parameters

name	Type	Required	Description

name	String	yes	Name of the component to register

comp	Object	yes	The component to register

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

[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]

removeClass( classToRemove )

Remove a CSS class name from the component's element

Parameters

name	Type	Required	Description

classToRemove	String	yes	Classname to remove

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

[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]

trigger( event, [hash] )

Trigger an event on an element

    myComponent.trigger('eventName');
    myComponent.trigger({'type':'eventName'});
    myComponent.trigger('eventName', {data: 'some data'});
    myComponent.trigger({'type':'eventName'}, {data: 'some data'});

Parameters

name	Type	Required	Description

event	Event|Object|String	yes	A string (the type) or an event object with a type attribute

hash	Object	no	data hash to pass along with the event

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

[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]