0
# Event System
1
2
Video.js provides a comprehensive event system for handling media events, user interactions, and component communication, built on standard DOM events with additional Video.js-specific events.
3
4
## Capabilities
5
6
### Event Management Functions
7
8
Global event handling functions for managing events across Video.js components.
9
10
```javascript { .api }
11
/**
12
* Add event listener to target
13
* @param target - Event target (element, component, or player)
14
* @param type - Event type or space-separated types
15
* @param listener - Event handler function
16
*/
17
videojs.on(target: EventTarget, type: string, listener: EventListener): void;
18
19
/**
20
* Add one-time event listener
21
* @param target - Event target
22
* @param type - Event type or space-separated types
23
* @param listener - Event handler function
24
*/
25
videojs.one(target: EventTarget, type: string, listener: EventListener): void;
26
27
/**
28
* Remove event listener
29
* @param target - Event target
30
* @param type - Event type or space-separated types
31
* @param listener - Specific handler to remove (optional)
32
*/
33
videojs.off(target: EventTarget, type?: string, listener?: EventListener): void;
34
35
/**
36
* Trigger event on target
37
* @param target - Event target
38
* @param event - Event type string or Event object
39
* @param data - Additional event data
40
*/
41
videojs.trigger(target: EventTarget, event: string | Event, data?: any): void;
42
43
/**
44
* Listen to event on multiple targets
45
* @param targets - Array of event targets
46
* @param type - Event type
47
* @param listener - Event handler function
48
*/
49
videojs.any(targets: EventTarget[], type: string, listener: EventListener): void;
50
```
51
52
**Usage Examples:**
53
54
```javascript
55
// Add event listeners
56
videojs.on(player, 'play', () => {
57
console.log('Player started playing');
58
});
59
60
// Multiple event types
61
videojs.on(player, 'play pause', (event) => {
62
console.log('Playback state changed:', event.type);
63
});
64
65
// One-time listener
66
videojs.one(player, 'loadedmetadata', () => {
67
console.log('Metadata loaded - fires once');
68
});
69
70
// Remove listeners
71
videojs.off(player, 'play'); // Remove all play listeners
72
videojs.off(player); // Remove all listeners
73
74
// Trigger custom events
75
videojs.trigger(player, 'customEvent', { data: 'value' });
76
77
// Listen on multiple players
78
const players = [player1, player2, player3];
79
videojs.any(players, 'ended', () => {
80
console.log('One of the players finished');
81
});
82
```
83
84
### Player Events
85
86
Core player instance methods for event handling.
87
88
```javascript { .api }
89
/**
90
* Add event listener to player
91
* @param type - Event type or space-separated types
92
* @param listener - Event handler function
93
*/
94
on(type: string, listener: EventListener): void;
95
96
/**
97
* Add one-time event listener to player
98
* @param type - Event type or space-separated types
99
* @param listener - Event handler function
100
*/
101
one(type: string, listener: EventListener): void;
102
103
/**
104
* Remove event listener from player
105
* @param type - Event type or space-separated types
106
* @param listener - Specific handler to remove (optional)
107
*/
108
off(type?: string, listener?: EventListener): void;
109
110
/**
111
* Trigger event on player
112
* @param event - Event type string or Event object
113
* @param data - Additional event data
114
*/
115
trigger(event: string | Event, data?: any): void;
116
```
117
118
**Usage Examples:**
119
120
```javascript
121
// Player event listeners
122
player.on('play', function() {
123
console.log('Playing');
124
});
125
126
player.on('timeupdate', function() {
127
console.log('Current time:', this.currentTime());
128
});
129
130
// Context is the player
131
player.on('ended', function() {
132
console.log('Video ended, duration was:', this.duration());
133
});
134
135
// Event object contains additional info
136
player.on('error', function(event) {
137
console.error('Player error:', event.target.error());
138
});
139
```
140
141
### Media Events
142
143
Standard HTML5 media events fired by the player during playback.
144
145
```javascript { .api }
146
// Playback events
147
'loadstart' // Started loading media
148
'progress' // Downloading media data
149
'loadedmetadata' // Metadata loaded (duration, dimensions)
150
'loadeddata' // First frame loaded
151
'canplay' // Can start playing
152
'canplaythrough' // Can play without buffering
153
'playing' // Playback started after being paused
154
'waiting' // Waiting for data (buffering)
155
'seeking' // Seeking started
156
'seeked' // Seeking completed
157
'ended' // Playback completed
158
'durationchange' // Duration changed
159
'timeupdate' // Current time changed
160
'play' // Play() called
161
'pause' // Pause() called
162
'ratechange' // Playback rate changed
163
'resize' // Video dimensions changed
164
'volumechange' // Volume or muted state changed
165
166
// Loading events
167
'abort' // Loading aborted
168
'error' // Loading error occurred
169
'stalled' // Data loading stalled
170
'suspend' // Loading suspended
171
'emptied' // Media element emptied
172
173
// Text track events
174
'texttrackchange' // Text track mode changed
175
'cuechange' // Active cues changed
176
```
177
178
**Usage Examples:**
179
180
```javascript
181
// Track loading progress
182
player.on('loadstart', () => {
183
console.log('Started loading');
184
});
185
186
player.on('progress', () => {
187
const buffered = player.buffered();
188
if (buffered.length > 0) {
189
console.log('Buffered:', buffered.end(0), 'seconds');
190
}
191
});
192
193
player.on('canplay', () => {
194
console.log('Ready to play');
195
});
196
197
// Monitor playback
198
player.on('play', () => {
199
console.log('Playback started');
200
});
201
202
player.on('timeupdate', () => {
203
const currentTime = player.currentTime();
204
const duration = player.duration();
205
const progress = (currentTime / duration) * 100;
206
console.log('Progress:', progress.toFixed(1) + '%');
207
});
208
209
player.on('ended', () => {
210
console.log('Video finished');
211
});
212
213
// Handle errors
214
player.on('error', () => {
215
const error = player.error();
216
console.error('Playback error:', error.code, error.message);
217
});
218
```
219
220
### Component Events
221
222
Events specific to UI components and user interactions.
223
224
```javascript { .api }
225
// UI interaction events
226
'click' // Component clicked
227
'focus' // Component focused
228
'blur' // Component lost focus
229
'keydown' // Key pressed
230
'keyup' // Key released
231
'mouseenter' // Mouse entered component
232
'mouseleave' // Mouse left component
233
'touchstart' // Touch interaction started
234
'touchend' // Touch interaction ended
235
236
// Component lifecycle events
237
'componentresize' // Component resized
238
'ready' // Component ready
239
'dispose' // Component disposed
240
241
// Player-specific UI events
242
'userinactive' // User inactive (controls auto-hide)
243
'useractive' // User active (controls shown)
244
'fullscreenchange' // Fullscreen state changed
245
'enterFullWindow' // Entered full window mode
246
'exitFullWindow' // Exited full window mode
247
```
248
249
**Usage Examples:**
250
251
```javascript
252
// UI interaction handling
253
const playButton = player.getChild('ControlBar').getChild('PlayToggle');
254
playButton.on('click', () => {
255
console.log('Play button clicked');
256
});
257
258
// User activity monitoring
259
player.on('useractive', () => {
260
console.log('User is active - show controls');
261
});
262
263
player.on('userinactive', () => {
264
console.log('User inactive - hide controls');
265
});
266
267
// Fullscreen events
268
player.on('fullscreenchange', () => {
269
if (player.isFullscreen()) {
270
console.log('Entered fullscreen');
271
} else {
272
console.log('Exited fullscreen');
273
}
274
});
275
276
// Component resize
277
player.on('componentresize', () => {
278
console.log('Player resized to:', player.width(), 'x', player.height());
279
});
280
```
281
282
### Custom Events
283
284
Create and handle custom events for application-specific functionality.
285
286
```javascript { .api }
287
// Trigger custom events with data
288
player.trigger('qualitychange', {
289
oldQuality: '720p',
290
newQuality: '1080p'
291
});
292
293
player.trigger('adstart', {
294
duration: 30,
295
skipTime: 5
296
});
297
298
// Listen for custom events
299
player.on('qualitychange', (event, data) => {
300
console.log('Quality changed from', data.oldQuality, 'to', data.newQuality);
301
});
302
303
player.on('adstart', (event, data) => {
304
console.log('Ad started, duration:', data.duration, 'seconds');
305
setTimeout(() => {
306
player.trigger('adskippable');
307
}, data.skipTime * 1000);
308
});
309
```
310
311
### Event Delegation
312
313
Handle events from child components through event delegation.
314
315
```javascript { .api }
316
// Listen for button clicks on control bar
317
const controlBar = player.getChild('ControlBar');
318
controlBar.on('click', function(event) {
319
const target = event.target;
320
console.log('Control bar button clicked:', target.className);
321
});
322
323
// Handle menu item selection
324
const menuButton = player.getChild('ControlBar').getChild('PlaybackRateMenuButton');
325
if (menuButton) {
326
menuButton.on('click', function(event) {
327
if (event.target.tagName === 'LI') {
328
console.log('Playback rate selected:', event.target.textContent);
329
}
330
});
331
}
332
```
333
334
### Event Data and Context
335
336
Access event information and maintain proper context in event handlers.
337
338
```javascript { .api }
339
// Event handler context
340
player.on('play', function(event) {
341
// 'this' refers to the player
342
console.log('Player ID:', this.id());
343
console.log('Current source:', this.currentSrc());
344
345
// Event object properties
346
console.log('Event type:', event.type);
347
console.log('Event target:', event.target);
348
console.log('Timestamp:', event.timeStamp);
349
});
350
351
// Arrow functions don't bind 'this'
352
player.on('pause', (event) => {
353
// Use event.target or direct player reference
354
console.log('Paused at:', event.target.currentTime());
355
console.log('Paused at:', player.currentTime());
356
});
357
358
// Event with custom data
359
player.on('customEvent', function(event, data) {
360
console.log('Custom event data:', data);
361
console.log('Player state:', this.paused() ? 'paused' : 'playing');
362
});
363
```
364
365
### Error Event Handling
366
367
Comprehensive error handling with detailed error information.
368
369
```javascript { .api }
370
// Media errors
371
player.on('error', function() {
372
const error = this.error();
373
374
switch (error.code) {
375
case 1: // MEDIA_ERR_ABORTED
376
console.log('Media loading aborted');
377
break;
378
case 2: // MEDIA_ERR_NETWORK
379
console.log('Network error');
380
break;
381
case 3: // MEDIA_ERR_DECODE
382
console.log('Media decode error');
383
break;
384
case 4: // MEDIA_ERR_SRC_NOT_SUPPORTED
385
console.log('Media format not supported');
386
break;
387
default:
388
console.log('Unknown error:', error.message);
389
}
390
});
391
392
// Custom error handling
393
player.on('networkerror', function(event, data) {
394
console.log('Network error details:', data);
395
// Implement retry logic or fallback source
396
});
397
```
398
399
### Performance Monitoring
400
401
Use events to monitor player performance and user engagement.
402
403
```javascript { .api }
404
// Track loading performance
405
let loadStartTime;
406
player.on('loadstart', () => {
407
loadStartTime = Date.now();
408
});
409
410
player.on('canplay', () => {
411
const loadTime = Date.now() - loadStartTime;
412
console.log('Load time:', loadTime, 'ms');
413
});
414
415
// Track user engagement
416
let watchTime = 0;
417
let lastTime = 0;
418
419
player.on('play', () => {
420
lastTime = player.currentTime();
421
});
422
423
player.on('timeupdate', () => {
424
if (!player.paused()) {
425
const currentTime = player.currentTime();
426
watchTime += Math.max(0, currentTime - lastTime);
427
lastTime = currentTime;
428
}
429
});
430
431
player.on('pause ended', () => {
432
console.log('Total watch time:', watchTime, 'seconds');
433
});
434
```
435
436
## Types
437
438
```javascript { .api }
439
interface EventListener {
440
(event: Event, ...args: any[]): void;
441
}
442
443
interface Event {
444
type: string;
445
target: EventTarget;
446
currentTarget: EventTarget;
447
timeStamp: number;
448
preventDefault(): void;
449
stopPropagation(): void;
450
stopImmediatePropagation(): void;
451
}
452
453
interface EventTarget {
454
addEventListener(type: string, listener: EventListener): void;
455
removeEventListener(type: string, listener: EventListener): void;
456
dispatchEvent(event: Event): boolean;
457
}
458
459
// Media error codes
460
interface MediaError {
461
code: number;
462
message: string;
463
MEDIA_ERR_ABORTED: 1;
464
MEDIA_ERR_NETWORK: 2;
465
MEDIA_ERR_DECODE: 3;
466
MEDIA_ERR_SRC_NOT_SUPPORTED: 4;
467
}
468
469
// Common event types
470
type MediaEventType =
471
| 'loadstart' | 'progress' | 'loadedmetadata' | 'loadeddata'
472
| 'canplay' | 'canplaythrough' | 'playing' | 'waiting'
473
| 'seeking' | 'seeked' | 'ended' | 'durationchange'
474
| 'timeupdate' | 'play' | 'pause' | 'ratechange'
475
| 'resize' | 'volumechange' | 'abort' | 'error'
476
| 'stalled' | 'suspend' | 'emptied';
477
478
type PlayerEventType = MediaEventType
479
| 'ready' | 'dispose' | 'useractive' | 'userinactive'
480
| 'fullscreenchange' | 'componentresize';
481
482
type ComponentEventType =
483
| 'click' | 'focus' | 'blur' | 'keydown' | 'keyup'
484
| 'mouseenter' | 'mouseleave' | 'touchstart' | 'touchend';
485
```