Sub topic 13
Reacting to media events
This chapter assumes you can select elements and attach event listeners in JavaScript. It also assumes you know how play() and pause() work on a media element.
The working model
An <audio> or <video> element is a state machine. When its state changes, it fires an event on the element. Your code listens for these events instead of polling currentTime or paused on a timer.
Media events do not bubble. Attach listeners to the media element itself, not to a parent.
Loading events
Loading follows a predictable order.
| Event | Meaning |
|---|---|
| `loadedmetadata` | Duration and video dimensions are known |
| `loadeddata` | The first frame at the current position is available |
| `canplay` | Playback can start, but may stall to buffer |
| `canplaythrough` | The browser estimates it can play to the end without stalling |
Playback events
| Event | When it fires |
|---|---|
| `play` | Playback was requested, or `autoplay` started it |
| `playing` | Playback is actually running |
| `pause` | The element paused |
| `waiting` | Playback stopped because data is missing |
| `seeking`, `seeked` | A seek started, and a seek finished |
| `timeupdate` | `currentTime` changed |
| `ended` | Playback reached the end |
| `error` | Loading or decoding failed |
play and playing are different. play fires when playback is requested. playing fires only once frames are advancing. Use waiting and playing to show and hide a buffering spinner.
A progress bar
This example reads the duration only after metadata has loaded, and updates a <progress> element as time advances.
<video id="player" controls src="clip.mp4"></video>
<progress id="progress" value="0" max="1"></progress>
<script>
const video = document.querySelector('#player');
const progress = document.querySelector('#progress');
function setMax() {
progress.max = video.duration;
}
if (video.readyState >= 1) {
setMax();
} else {
video.addEventListener('loadedmetadata', setMax);
}
video.addEventListener('timeupdate', () => {
progress.value = video.currentTime;
});
video.addEventListener('ended', () => {
console.log('Playback finished');
});
video.addEventListener('error', () => {
console.error('Media error code:', video.error && video.error.code);
});
</script>The readyState check covers a cached file whose metadata loaded before your script ran. Without it, the listener never fires and max stays at 1.
Common errors
- Reading
durationtoo early. It isNaNbeforeloadedmetadata. For live streams it can beInfinity. - Adding listeners too late. Events that already fired do not fire again. Check
readyStateas shown above. - Expecting
endedon a looping element. Withloop, the element restarts andendeddoes not fire. - Treating
timeupdateas frame-accurate. It fires a few times per second, and the rate varies by browser. Use it for UI such as progress bars, not for precise synchronization. - Listening for
erroron<source>. When you use<source>children, load failures fireerroron the<source>element, not on the parent media element. The event does not bubble, so attach the listener to each<source>.
Exercise
A page sets progress.max = video.duration right after the script runs, but the progress bar never fills correctly for cached videos. Why does listening for loadedmetadata alone not fix it, and what is the fix?
Show answer
For a cached video, metadata may already be loaded before the listener is attached, so loadedmetadata never fires again. Check video.readyState >= 1 and set max immediately if true. Otherwise add the loadedmetadata listener.